26 June 2013

What is onbeforeunload?

Accourding to MDN docs its an event which fires when a page is about to be unloaded. This event is cancelable and is presented as a modal box to the user. Here is the image of the modal box shown by jsfiddle.net when someone tries to navigate away.


onbeforeunload


How to we assign a handler to onbeforeunload event?

Attaching an event handler to the onbeforeunload event is dead simple. Here's the code.

window.onbeforeunload=function(){
    return "Make sure you have saved everything before leaving this page.";
}

This code will show the message in the modal box presented by the browser.

What is the problem on IE?

Suppose we have a event handler attached for onbeforeunload event and we also have links on our page which looks something like the code below.

<a href="javascript:void(0)" onclick="save();">Save</a>

IE invokes the onbeforeunload handler before even executing our code in save function. Its a bit wired as this does not happen in other browsers like Chrome,FF,Safari.



Solution

Workaround to this problem can be change the a tags to span tags and make your code look like this.

<span class="linkposer" onclick="save();">Save</span>

We can style our class that it looks likes a Link with text-decoration, color and cursor.


More Information



blog comments powered by Disqus