1

I tried my code on chrome, opera, firefox and edge but it's not working. My onload code works perfectly, but onunload doesn't work on all. Do not know why?

Here is my code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body  onload="loaded()" onunload="unloaded()">
    
    <script type="text/javascript">
      function loaded(){
        alert("The page loaded!");
      }

      function unloaded(){
        alert("Come again!");
      }
    </script>

  </body>
</html>
Pawel Uchida-Psztyc
  • 3,735
  • 2
  • 20
  • 41
klavyeadam
  • 123
  • 1
  • 3
  • 9
  • What are you expecting to happen? The browser doesn't allow you to display alert boxes when the page is being closed. – Lennholm May 16 '17 at 12:20
  • 2
    Possible duplicate of [window.onunload is not working properly in Chrome browser. Can any one help me?](http://stackoverflow.com/questions/7794301/window-onunload-is-not-working-properly-in-chrome-browser-can-any-one-help-me) – Samuil Petrov May 16 '17 at 12:21
  • Behaviour is simillar for other browsers – Samuil Petrov May 16 '17 at 12:22
  • The onunload is working as expected. add this window.open("http://www.google.com") in unloaded() function and confirm. – Aefits May 16 '17 at 13:41

2 Answers2

1

Some operations are not allowed on onunload event showing alert is one of them. Check this answer.

You can use below code to display a warning message to users.

window.onbeforeunload = function(e) {
  return 'Bye now!';
}; 
Community
  • 1
  • 1
Aefits
  • 3,399
  • 6
  • 28
  • 46
0

when you invoke the unload function,the DOM is completely unload now. So there can't show an alert window for you. But you can see the log printed in the console if you use ---> console.info("Come again!");

Jerry.Y
  • 1
  • 2