【问题标题】:Declare and initialize global variable in iframe scope using Javascript (same domain)使用 Javascript(同域)在 iframe 范围内声明和初始化全局变量
【发布时间】:2016-12-15 12:47:11
【问题描述】:

关于如何访问 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>

谢谢!

【问题讨论】:

    标签: javascript html iframe scope global-variables


    【解决方案1】:

    你有 3 个问题。

    1. 在尝试修改其 DOM 之前,您无需等待 iframe 中的文档加载
    2. 在尝试读取之前,您无需等待设置属性
    3. 您正在document 上设置属性,但正试图从window 读取它

    所以:

    <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>
    

    【讨论】:

    • 谢谢@Quentin。我想我在您回复时编辑了我的问题。你会注意到我知道document.myGlobalVariable 可以工作,但我怎么能拥有它,所以它只是在全局范围内(我猜是窗口的?),这样我就可以通过myGlobalVariable 引用它而无需document在前面?
    • 另外,感谢您指出我的加载顺序问题。在我的实际代码中,我使用 jQuery 等待文档加载,然后再运行 iframe 的 JS。我已将其添加到我的问题中,以免分散我的实际问题。
    • 知道了。需要将其添加到窗口范围。添加了我的答案并将接受它。赞成您的回答。
    【解决方案2】:

    回答我自己的问题:

    我试图将变量添加到 document 范围,如下所示:

    iframe.contentDocument.myGlobalVariable = "Hello";

    但是将其添加到文档范围意味着,为了从 iframe 的 JS 中引用变量,您必须将 document. 附加到变量的前面:document.myGlobalVariable

    但正如我的问题所述,我希望能够仅通过变量名来引用它:myGlobalVariable

    为此,您只需将其添加到 window 范围即可:

    iframe.contentWindow.myGlobalVariable = "Hello";

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 2017-08-19
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      相关资源
      最近更新 更多