首页 > 解决方案 > document.getElementById 在 Google Web 应用程序中以一种奇怪的方式工作

问题描述

我正在学习谷歌脚本,我已经创建了一个简单的网络应用程序。使用它(客户端),在 Google Chrome 导航器中观察到蠕变行为(对我来说):

尝试使用命令通过控制台获取元素document.getElementById("ID of a active Element"),但未找到元素。但是,在使用检查器工具(在 FireFox 和 Chrome 中为 ctrl+c,并确保存在此类 ID)对其进行分析后,该元素变为可访问的,并且通过简单地重复 fetch 命令(document.getElementById("ID of a active Element")),发生预期的返回,这意味着,函数正常工作,找到元素。我不知道为什么以及如何发生这种行为。

问题:为什么会有这种行为?我怎样才能安全地创建或避免它?

系统信息:Linux debian 4.9.0-11-amd64 #1 SMP Debian 4.9.189-3+deb9u2 (2019-11-11) x86_64 GNU/Linux

PS:在 FireFox 中,它总是返回 null,即使在检查元素之后!Chrome 的行为是稳定的(在检查之前没有发现,在之后发现)。

提前致谢。

一个链接,如果你想体验这种行为

下面,上面页面的代码。doGet 函数仅返回该页面。没有什么比这更多了。

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <style>
     body{ display: grid; align-items: center; }
     button { padding-left: 40%;padding-right: 40%; }
    </style>
  </head>
  <body>
  <h1> Thank you for your support! </h1>
  <p> The button below has ID <strong>bbb</strong>. Try to find it in console with the command <span >document.getElementById("bbb")</span>. In Chrome, you will get null. But, after inspect the element (ctrl+c and click over it), you will get the button.</p>
    <button id="bbb"> My ID is bbb - click on me to copy the mentioned command above. </button>
  <p> If you try <strong>document.body.getElementsByTagName("IFRAME")[0].contentWindow.document.getElementById('bbb')</strong>, you will fail due to lack of permissions</p>
  <button id="fff"> My ID is fff - click on me to copy the mentioned command above.</button>
  </body>
  <script>
//the code of copyToClipboard was copied from https://www.30secondsofcode.org/blog/s/copy-text-to-clipboard-with-javascript only used to illustrate this question.
  const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};
  document.getElementsByTagName("BUTTON")[0].onclick = function(){ copyToClipboard( 'document.getElementById("bbb")' )};
document.getElementsByTagName("BUTTON")[1].onclick = function(){ copyToClipboard( 'document.body.getElementsByTagName("IFRAME")[0].contentWindow.document.getElementById("fff")' )};
  </script>
</html>

标签: javascriptdomgoogle-apps-scriptweb-applications

解决方案


要在 iframe 的上下文中使用控制台,请在 Firefox 的窗口图标chrome 的“顶部”栏中选择您需要连接的 iframe 。

您的 html 所在的框架是带有 src 的框架https://*-script.googleusercontent.com


推荐阅读