Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Javascript function before browser reloads/closes browser/exits page?

Tags:

javascript

Is there a way to execute a function before a user chooses to reload/close browser/exit page?

I need this for an "online/offline" status function i am trying to write. I want to detect whether the user is still on the page or not.

Any ideas? :)

Maybe there is a better approach to this?

like image 379
Alosyius Avatar asked Feb 07 '13 08:02

Alosyius


1 Answers

Inline function:

window.onbeforeunload = function(evt) {

    // Cancel the event (if necessary)
    evt.preventDefault();

    // Google Chrome requires returnValue to be set
    evt.returnValue = '';

    return null;
};

or via an event listener (recommended):

window.addEventListener("beforeunload", function(evt) {

    // Cancel the event (if necessary)
    evt.preventDefault();

    // Google Chrome requires returnValue to be set
    evt.returnValue = '';

    return null;
});

or if you have jQuery:

$(window).on("beforeunload", function(evt) {

    // Cancel the event (if necessary)
    evt.preventDefault();

    // Google Chrome requires returnValue to be set
    evt.returnValue = '';

    return null;
});

Notes:

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog.

Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm() and window.prompt() methods may be ignored during this event.

See documentation at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

like image 114
Samuel Liew Avatar answered Nov 18 '22 09:11

Samuel Liew