onpagehide Event

Example

Call a function when the user is navigating away from a webpage:

<body onpagehide="myFunction()">


Description

The onpagehide event occurs when the user is navigating away from a webpage.

There are several ways to navigate away from a page. E.g. by clicking on a link, refreshing the page, submitting a form, closing the browser window, etc.

The onpagehide event is sometimes used instead of the onunload event, as the onunload event causes the page to not be cached.

To find out if a page is loaded directly from the server or if the page is cached, you can use the persisted property of the PageTransitionEvent object. This property returns true if the page is cached by the browser, and false otherwise.


Browser Support

The numbers in the table specify the first browser version that fully supports the event.

Event
onpagehide Yes 11.0  Yes 5.0 Yes

Note: Due to different browser settings, this event may not always work as expected.



Syntax

In HTML:

<element onpagehide="myScript">

In JavaScript:

object.onpagehide = function(){myScript};

In JavaScript, using the addEventListener() method:

object.addEventListener("pagehide", myScript);

Technical Details

Bubbles: No
Cancelable: No
Event type: PageTransitionEvent
HTML tags: <body>
DOM Version: Level 3 Events

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.