klavyeadam
klavyeadam

Reputation: 123

onunload on body is not working

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>

Upvotes: 1

Views: 5454

Answers (2)

Aefits
Aefits

Reputation: 3469

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!';
}; 

Upvotes: 1

Jerry.Y
Jerry.Y

Reputation: 1

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!");

Upvotes: 0

Related Questions