admin管理员组

文章数量:1193808

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?

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?

Share Improve this question asked Feb 7, 2013 at 8:38 AlosyiusAlosyius 9,11126 gold badges78 silver badges121 bronze badges 2
  • window.onbeforeunload = function () {...} – Moritz Roessler Commented Feb 7, 2013 at 8:39
  • 2 window.onbeforeunload, reference: developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload – PatrikAkerstrand Commented Feb 7, 2013 at 8:44
Add a comment  | 

3 Answers 3

Reset to default 23

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

Use window.onbeforeunload, it is triggered when user leaves your page :http://geekswithblogs.net/hmloo/archive/2012/02/15/use-window.onbeforeunload-event-to-stop-browser-from-closing-or-disable.aspx

Try this:

$( window ).unload(function() {
  alert( "Handler for .unload() called." );
});

OR this if you want conformation alert

<script>
window.onbeforeunload = function(e) {  
   return 'Your dialog message';
};
</script>

本文标签: Execute Javascript function before browser reloadscloses browserexits pageStack Overflow