Skip to content Skip to sidebar Skip to footer

Event To Be Triggered When Leaving Website Or Closes The Browser

I´m trying for a while execute a javascript function when a user leaves web site by typing a address in the browser and hits return or the user closes the brower clicking in the '

Solution 1:

You can listen to beforeunload event that fires before the unload event, when the page is unloaded.

$(window).on('beforeunload', function(){
    // ...
})

Solution 2:

Some browsers (like Chrome) block alerts in unload event handlers, to prevent exactly these kind of annoying messages. Try a console.log or put a breakpoint in to find out if the handler is triggered when you don't have an alert there.

SO question on a similar line:

window.onunload is not working properly in Chrome browser. Can any one help me?

You can only pass the alert by returning a string in a beforeunload handler (HT @undefined), but I would avoid even that, because popups are generally bad, and most people will do minimum processing to work out the make-this-thing-go-away option before they actually think about the contents of the box.

Solution 3:

The function you defined in window.onbeforeunload if it returns a string it will pop up a confirm navigation prompt with that message.

Alerts may be ignored!

window.onbeforeunload = function() {
    return"All unsaved data will be lost. Are you sure?";
};

Some browsers handle the onbeforeunload differently. Recent Firefox for example will ignore your return string and just display a standard message.

Solution 4:

$(window).bind('beforeunload', function(){
    alert("Are your sure?")
});

Post a Comment for "Event To Be Triggered When Leaving Website Or Closes The Browser"