HTML | DOM onpagehide Event

The DOM onpagehide event in HTML occurs when the user is getting off from a webpage. for example, close the browser window, click on the link, refresh the page, etc.

The page to not be cached in onunload event, onpagehide event used instead of the onunload event.

Syntax:



  • In HTML:
    <element onpagehide="myScript">
  • In JavaScript:
    object.onpagehide = function(){myScript};
  • In JavaScript, using the addEventListener() method:
    object.addEventListener("pagehide", myScript); 

Example 1: using Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>
           DOM onpagehide event
        </title>
    </head>
<body>
  
<h1 id="hID"></h1>
  
<script>
document.getElementsByTagName(
    "BODY")[0].onpagehide = function()
    {GFGfun()};
  
function GFGfun() {
  document.getElementById(
      "hID").innerHTML = "Thank you!";
};
  
</script>
  
</body>
</html>

chevron_right


Example 2: Using the addEventListener() method

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
        <head>
        <title>
           DOM onpagehide event
        </title>
    </head>
<body>
  
  
<h1 id="hID"></h1>
  
<script>
window.addEventListener("pagehide", GFGfun);
  
function GFGfun() {
  document.getElementById(
      "hID").innerHTML = "Thank You";
}
</script>
  
</body>
</html>

chevron_right


Supported Browsers: The browsers supported by DOM onpagehide Event are listed below:

  • Google Chrome
  • Internet Explorer 11.0
  • Firefox
  • Apple Safari 5.0
  • Opera


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.