使加载在IFRAME中的页面访问包含页面的JavaScript对象'的脚本

Make a page loaded in an IFRAME access the JavaScript objects of the containing page's script

本文关键字:对象 JavaScript 脚本 包含页 访问 IFRAME 加载      更新时间:2023-09-26

我有一个名为Parent.HTML的HTML页面,它有一些内联JavaScript代码,它还有一个IFRAME,它在其中加载另一个名称为Child.HTML的页面。

我希望Child.html中的JavaScript代码能够引用Parent.html中声明的JavaScript对象。

这可能吗?我试过了,但没用。请参阅下面的代码。

Parent.html

<html>
    <head>
        <script src = "jQuery.js" type = "text/javascript"></script>
        <script>
            var Foo = 
            {
                Initialize: function()
                {
                    alert('Hello, I am Foo.');
                },
                SomeVariable : 'I am a property of the Foo class.'
            };
            $(document).ready( function() { Foo.Initialize(); } );
        </script>
    </head>
    <body>
        <h1>Parent</h1>
        <p>This is the parent Web page.</p>
        <p>
            <IFRAME src = "child.html" height = "400" width = "800"></IFRAME>
        </p>
    </body>
</html>

Child.html

<html>
    <head>
        <script type = "text/javascript">
            $(document).ready( function() { Foo.Initialize(); alert(Foo.SomeVariable); } );
        </script>
    </head>
    <body>
        <h4>Child</h4>
        <p>This is the child Web page.</p>
        <p>
            I am a child.
            <script>
            </script>
        </p>
    </body>
</html>

有没有一种方法可以让这些页面在它们之间共享数据?

window.top.Foo.Initialize()window.parent.Foo.Initialize()

请参阅https://developer.mozilla.org/en-US/docs/Web/API/window.parent?redirectlocale=en-美国&重定向段塞=DOM%2window.parent

请注意,跨窗口访问受同源策略的约束