window.onbeforeunload and window.location.href in IE
Asked Answered
E

1

8

We are using window.location.href to navigate the user to a page. Also, we have configured the window.onbeforeunload event to alert users in case there are any unsaved changes.

window.onbeforeunload = confirmBeforeClose;

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

In places where there are unsaved changes, and I try to use window.location.href to navigate the user, I get the alert message.

It works fine if I click OK on the popup. However, if I click CANCEL, the JS throws an unspecified error at window.location.href.

Any help is appreciated.

Eckert answered 23/3, 2010 at 12:41 Comment(2)
Please show the code where you are doing the location.href.Capablanca
I can only reproduce this in IE7. I confirmed that FF 3.6, Chrome 4, and IE8 do not throw an error (did not test IE6). Please add IE7 as part of the question or title.Lambrecht
L
11

I was also experiencing this issue (in IE7 and above, not in IE6 however).

The only solution that I could find was wrapping the window.location.href call in a try/catch block.

The below is a complete example that reproduces the problem. If you uncomment out the try/catch then it works as desired in all browsers.

JavaScript (in HTML head):

  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 ) { }
  }

HTML:

<body>
 <a href="#" onclick="leavePage(); return false;">Leave this page</a> 
</body>
Lambrecht answered 28/4, 2010 at 18:49 Comment(3)
For future visitors: This just fixed it for me on IE9 now as well, so it's clearly not IE7 only.Cinthiacintron
...and for IE11 as well!Rahmann
This works for me window.location.href but window.location doesn't.Celie

© 2022 - 2024 — McMap. All rights reserved.