javascript - 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>
解决方案
要在 iframe 的上下文中使用控制台,请在 Firefox 的窗口图标或chrome 的“顶部”栏中选择您需要连接的 iframe 。
您的 html 所在的框架是带有 src 的框架https://*-script.googleusercontent.com
。
推荐阅读
- python - 如何制作一个同样明智的按钮 django
- laravel - 使用数组的 Laravel Eloquent 关系映射
- javascript - OnClick 更改按钮文本和 URL
- spring - 有没有办法在 Spring Boot 中测试没有 Web 或持久层的嵌套对象?
- pdf - 在 Google Cloud Functions 上使用 GraphicsMagick (GM) 操作 PDF 时出现权限错误
- java - 如何使用 java 在 Azure Blob 存储中的容器之间移动(或复制)blob
- performance - 用于性能分析的低硬件仿真
- python - 如何在python中解压数据
- python - 数据抓取输出到数据框
- python - 如何在其他类中添加多对多关系。就我而言,在 InfoCreateView 类中