7

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!");
};
Hamed Kamrava
  • 12,359
  • 34
  • 87
  • 125
  • possible duplicate of [javascript to check when the browser window is close](http://stackoverflow.com/questions/805463/javascript-to-check-when-the-browser-window-is-close) – Quentin Jul 22 '13 at 14:34
  • 2
    How about `window.onbeforeunload`? – tymeJV Jul 22 '13 at 14:34

3 Answers3

23

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.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
1

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 :'( )

Tom Metcalfe
  • 308
  • 1
  • 3
  • 12
0

Use body or document instead of window.

Pieter
  • 1,823
  • 1
  • 12
  • 16