Search code examples
javascriptonbeforeunload

Bind an event with onbeforeunload


I use the following code to prompt a message if the user close the page :

window.onbeforeunload = function(e) {
    e = e ? e : window.event;
    if(e) { 
        e.returnValue = ''; 
    }
    return '';
}

I would like to avoid the prompt this message shows when a user clicks a special link (let say id="myid") on the page. Is it possible? I tried like this:

var source = e.target || e.srcElement;
console.log(source);

But source is null, is it possible to bind the event and to check it with onbeforeunload?

and what are the "e" attributes ? how I can look into this "object" ? Any idea ?


Solution

  • Unbind the event if the link is clicked and then redirect

    window.onbeforeunload = null;