Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.unload() won't work in jQuery

I'm trying to alert something out after closing page.

A simple window.unload example as below :

HTML

<html>
<body>
  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
  <script src="test.js" type="text/javascript">
</html>

test.js

$(window).unload( function () { 
    alert("Bye now!"); 
});

P.S :

I have tried javascript too, but doesn't alert anything out !

test.js

window.onunload = function() {
    alert("Bye now!");
};
like image 964
Hamed Kamrava Avatar asked Jul 22 '13 14:07

Hamed Kamrava


Video Answer


2 Answers

Most browsers prevent alert in unload. The best you can do is to use an onbeforeunload handler that returns a string - the browser will show that string to the user:

window.onbeforeunload = function() {
    return "Bye now!";
};

Demo here.

like image 146
RichieHindle Avatar answered Sep 23 '22 05:09

RichieHindle


What browser are you testing this code in ?

If you check the following link from W3School, Opera and Chrome do not support it. LINK

And a working example for onbeforeunload is to use jquery as following :

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

(I was going to comment this last bit on the above post but I cannot yet comment :'( )

like image 44
Tom Metcalfe Avatar answered Sep 23 '22 05:09

Tom Metcalfe