window.onbeforeunload,但对于一个框架?

时间:2010-11-08 15:09:15

标签: javascript frame frameset onbeforeunload

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

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

修改:它在Chrome 7或Safari 5中不起作用,但适用于Internet Explorer 8和FireFox 3.6。是否有修复/解决方法,以便我可以在Chrome 7和/或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(frameset)

<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 - 无法正常工作
  • FireFox 3.6.12 - 有效

1 个答案:

答案 0 :(得分:1)

在框架的上下文中,window指的是框架,它是一种窗口。因此window.onbeforeunload引用框架中窗口的事件,在卸载根页面时不会触发该事件。您可以通过window.top引用根窗口,或者通过window.parent引用框架的直接父窗口。但是,这些不是标准属性,因此请自行使用它们!