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

前端之家收集整理的这篇文章主要介绍了html – IE中的window.onbeforeunload和window.location.href前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们使用window.location.href将用户导航到页面.
此外,我们已配置window.onbeforeunload事件,以便在存在任何未保存的更改时提醒用户.
  1. window.onbeforeunload = confirmBeforeClose;
  2.  
  3. function confirmBeforeClose() {
  4. if (jwd.global.inEditMode)
  5. return "Your changes will not be saved :) and you will be punished to death";
  6. }

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

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

任何帮助表示赞赏.

解决方法

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

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

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

JavaScript(HTML头文件):

  1. window.onbeforeunload = confirmBeforeClose;
  2.  
  3. function confirmBeforeClose( )
  4. {
  5. return 'You have made changes on this page that will be lost if you navigate away without saving.';
  6. }
  7.  
  8. function leavePage( )
  9. {
  10. // try {
  11. window.location.href = "http://www.example.com";
  12. // } catch( e ) { }
  13. }

HTML:

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

猜你在找的HTML相关文章