onpagehide Event

Definition and Usage

The onpagehide event occurs when the user leaves the web page.

There are many ways to leave a page. For example, by clicking a link, refreshing the page, submitting a form, closing the browser window, etc.

The onpagehide event may be used instead onunload Event, because the onunload event may cause the page not to be cached.

To determine whether the page is loaded directly from the server or cached, you can use the PageTransitionEvent object's Persisted Property. If the page is cached by the browser, this property returns true; otherwise, it returns false (see more examples below).

Example

Execute JavaScript When User Leaves the Web Page:

<body onpagehide="myFunction()">

Syntax

In HTML:

<element onpagehide="myScript">

Try It Yourself

In JavaScript:

object.onpagehide = function(){myScript};

Try It Yourself

In JavaScript, use the addEventListener() method:

object.addEventListener("pagehide", myScript);

Try It Yourself

Note:Internet Explorer 8 or earlier versions do not support addEventListener() Method.

Technical Details

Bubbling: Not Supported
Cancelable: Not Supported
Event Type: PageTransitionEvent
Supported HTML Tags: <body>
DOM Version: Level 3 Events

Browser Support

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

Event Chrome IE Firefox Safari Opera
onpagehide Support 11.0 Support 5.0 Support

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