Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onbeforeunload and window.location.href in IE

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.

like image 549
Zuber Avatar asked Mar 23 '10 12:03

Zuber


People also ask

What is the difference between Onbeforeunload and Onunload?

onbeforeunload Below are my findings on the iPad; Using window. onunload , I am able to get an alert when user navigates to a different page from myPage. html (either by clicking on some link or doing a Google search while on myPage.

What is window Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

What is Beforeunload event?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.


1 Answers

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>
like image 121
Nick B Avatar answered Oct 05 '22 17:10

Nick B