代码之家  ›  专栏  ›  技术社区  ›  Lasse V. Karlsen

window.onbeforeunload,但是为了一个框架?

  •  5
  • Lasse V. Karlsen  · 技术社区  · 14 年前

    我试图发布一条关于离开网页的警告消息,但它嵌套在框架集中。

    显然,window.onbeforeunload如果我在浏览器中将网页作为根页面加载,则会触发触发器,但在框架集中加载时不会触发。

    编辑 :它在Chrome7或Safari 5中不起作用,但在InternetExplorer8和火狐3.6中起作用。是否有修复/解决方案,以便我可以让它在Chrome7和/或Safari 5中工作?

    我做错什么了?

    这就是我所尝试的:

    function closePageWarning()
    {
        return "Are you sure you want to leave this page?"
    }
    
    window.onbeforeunload = closePageWarning
    

    试验文件:

    test1.html(带有unbeforeunload脚本的页面)

    <html>
        <body>
            <script language="javascript">
            function closePageWarning()
            {
                return "Are you sure you want to leave this page?";
            }
    
            window.onbeforeunload = closePageWarning;
            </script>
            <a href="http://www.bitbucket.org">bitbucket</a>
        </body>
    </html>
    

    test2.html(框架集)

    <html>
        <frameset cols="20%, 80%">
            <frame name="menu" src="test3.html" />
            <frame name="content" src="test1.html" />
        </frameset>
    </html>
    

    test3.html(菜单,用脚本触发帧更改)

    <html>
        <body>
            <a target="content" href="http://www.bitbucket.org">bitbucket</a>
        </body>
    </html>
    

    如何测试:

    • 在浏览器中加载test1.html,然后单击链接,注意您得到了问题。
    • 在浏览器中加载test2.html,单击任意一个链接,注意没有问题。

    试验地点:

    • Google Chrome 7.0.517.44-不工作
    • Internet Explorer 8.0.7600.16385- 作品
    • Safari 5.0.2-不工作
    • 火狐3.6.12- 作品
    1 回复  |  直到 12 年前
        1
  •  1
  •   Eric Mickelsen    14 年前

    在框架的上下文中, window 指框架,它是一种窗口。所以 window.onbeforeunload 引用框架中窗口的事件,在卸载根页面时不会激发该事件。可以通过以下方式引用根窗口: window.top 或直接指向框架的父窗口 window.parent . 但是,这些不是标准属性,因此使用它们会有自己的危险!