IE中的window.onbeforeunload和window.location.href

Zub*_*ber 8 html window.location

我们使用window.location.href将用户导航到页面.此外,我们已配置window.onbeforeunload事件,以便在存在任何未保存的更改时提醒用户.

window.onbeforeunload = confirmBeforeClose;

function confirmBeforeClose() {
    if (jwd.global.inEditMode)
        return "Your changes will not be saved :) and you will be punished to death";
}
Run Code Online (Sandbox Code Playgroud)

在有未保存更改的地方,我尝试使用window.location.href导航用户,我收到警报消息.

如果我在弹出窗口中单击"确定",它可以正常工作.但是,如果我单击CANCEL,JS会在window.location.href处抛出一个未指定的错误.

任何帮助表示赞赏.

Nic*_*ick 11

我也遇到了这个问题(在IE7及更高版本中,但不是在IE6中).

我能找到的唯一解决方案是在try/catch块中包装window.location.href调用.

以下是重现问题的完整示例.如果您取消注释try/catch,那么它在所有浏览器中都可以正常工作.

JavaScript(HTML头文件):

  window.onbeforeunload = confirmBeforeClose;

  function confirmBeforeClose( )
  {
    return 'You have made changes on this page that will be lost if you navigate away without saving.';
  }

  function leavePage( )
  {
     // try {
          window.location.href = "http://www.example.com";
     // } catch( e ) { }
  }
Run Code Online (Sandbox Code Playgroud)

HTML:

<body>
 <a href="#" onclick="leavePage(); return false;">Leave this page</a> 
</body>

  • 对于未来的访问者:这也只是在IE9上为我修复它,所以它显然不是IE7. (2认同)