关于如何访问 iframe 中的全局变量提出了几个问题。我想知道如何在父级 iframe 范围内声明并初始化全局变量。我知道我可以使用 document.myGlobalVariable
从 iframe 访问该变量,但我希望能够通过说 myGlobalVariable
来引用它,而不需要 document .
在前面。
这是我的 HTML:
<html>
<head>...</head>
<body>
...
<iframe src="myFrame.html"></iframe>
<script type="text/javascript">
var iframe = document.querySelector('iframe');
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframeDocument.myGlobalVariable = "Hello";
</script>
</body>
</html>
myFrame.html
<html>
<body>
...
<script type="text/javascript">
// wait for document to load so parent script can finish running
$(function() {
console.log(document.myGlobalVariable); // <-- This works
console.log(myGlobalVariable); // <-- But this doesn't (and I want this one)
});
</script>
</body>
</html>
谢谢!
最佳答案
您有 3 个问题。
- 在尝试修改 DOM 之前,您无需等待 iframe 中的文档加载
- 在尝试读取属性之前,您不会等待属性设置完毕
- 您正在
文档
上设置属性,但尝试从窗口
读取它
所以:
<html>
<head>...</head>
<body>
...
<iframe src="myFrame.html"></iframe>
<script type="text/javascript">
var iframe = document.querySelector('iframe');
iframe.addEventListener("load", function () {
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframeDocument.myGlobalVariable = "Hello";
});
</script>
</body>
</html>
和
<html>
<body>
...
<script type="text/javascript">
setInterval(function () {
console.log(document.myGlobalVariable);
}, 1000);
</script>
</body>
</html>
关于javascript - 使用 Javascript 在 iframe 范围内声明并初始化全局变量(同一域),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41164557/