我正在学习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 GNULinux
P.S: 在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>