Javascript beforeunload detects update and close

Using the following function, you can determine which button the user clicks the refresh button or the close button? If there is no other way?

$(window).bind('beforeunload', function(event) { return 'pls save ur work'; }); 
+8
javascript html
source share
1 answer

The simple answer: security models without browsers do not allow you to explicitly determine how the user decided to leave your page (refresh / close / internal link / external link).

detect update browser for unloading / preloading when closing the browser

You can - with the help of cookies - check when the user loads your page, whether they were previously on this site in the same session - for example, to determine whether they have been updated, but not before the update:

Javascript browser update detection

Check if page reloads or refreshes in Javascript

A partial and imperfect approach will be to determine if they pressed "F5" or "Ctrl + R" or "Cmd + R" (shortcuts to refresh) just before the page was unloaded. This will detect some updates, but not where the user actually clicked the update button.

 (function($) { var refreshKeyPressed = false; var modifierPressed = false; var f5key = 116; var rkey = 82; var modkey = [17, 224, 91, 93]; // Check for refresh keys $(document).bind( 'keydown', function(evt) { // Check for refresh if (evt.which == f5key || window.modifierPressed && evt.which == rkey) { refreshKeyPressed = true; } // Check for modifier if (modkey.indexOf(evt.which) >= 0) { modifierPressed = true; } } ); // Check for refresh keys $(document).bind( 'keyup', function(evt) { // Check undo keys if (evt.which == f5key || evt.which == rkey) { refreshKeyPressed = false; } // Check for modifier if (modkey.indexOf(evt.which) >= 0) { modifierPressed = false; } } ); $(window).bind('beforeunload', function(event) { var message = "not refreshed"; if (refreshKeyPressed) { message = "refreshed"; } event.returnValue = message; return message; }); }(jQuery)); 

You can also determine when the link is clicked, whether the link is located on the same site or not: How to determine when a user leaves my site, and not just on another page?

+7
source share

All Articles