How to call a browser window or tab closing an event using jQuery

Is it possible to fire a window / tab close event using jQuery. I already tried using

$('selector').unload() 

But that did not work.

+4
source share
3 answers

You can use the unload() property of window in jQuery:

 $(window).unload(function() { //do stuff }); 

You don't need jQuery, but you can use a nice JavaScript style:

 window.onbeforeunload = function(e){ var msg = 'Are you sure?'; e = e || window.event; if(e) e.returnValue = msg; return msg; } 
+8
source

try it

 $(window).unload(function() { alert("Unload"); });​ 

Note. dialog boxes are blocked several times during unloading. You can check your console to confirm it.

0
source

In javascript

 window.onbeforeunload = function (event) { var message = 'Important: Please click on \'Save\' button to leave this page.'; if (typeof event == 'undefined') { event = window.event; } if (event) { event.returnValue = message; } return message; }; 

In jQuery

 $(window).on('beforeunload', function(){ return 'Are you sure you want to leave?'; }); 
0
source

Source: https://habr.com/ru/post/1493165/


All Articles