HTML onpagehide Attribute

Beginner
⏱️ 7 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onpagehide attribute is an inline event handler for the pagehide event on the window. It runs when the browser hides the page — for example when the user navigates away, closes the tab, or the page enters the back-forward cache (bfcache). Use it to save drafts, flush analytics, or release resources. The page is not always destroyed; check event.persisted in script. Pair with onpageshow when the page becomes visible again. Put onpagehide on <body> or use window.addEventListener("pagehide", …).

What You’ll Learn

01

Event handler

Inline JS.

02

pagehide

Page hidden.

03

window / body

Global scope.

04

event.persisted

bfcache hint.

05

+ onpageshow

Restore UX.

06

Save drafts

sessionStorage.

Purpose of onpagehide Attribute

The primary purpose of onpagehide is to run cleanup or save work when the user leaves the page — without blocking navigation the way onbeforeunload can. Common tasks include saving form drafts to sessionStorage, sending beacon analytics, closing WebSocket connections, or pausing timers.

The pagehide event fires on the window object. Unlike the legacy unload event, pagehide works well with the back-forward cache: the page may stay in memory and return instantly when the user clicks Back.

💡
Hidden ≠ destroyed

When event.persisted is true, the page was cached — do not assume all JavaScript state was reset. Use onpageshow to refresh stale data when the user returns.

📝 Syntax

Set onpagehide on body or assign window.onpagehide in JavaScript:

onpagehide.html
<body onpagehide="handlePageHide()" onpageshow="handlePageShow()"></body>

<script>
  window.onpagehide = handlePageHide;
  window.onpageshow = handlePageShow;
</script>

Syntax Rules

  • Value is JavaScript executed when the pagehide event fires on the window.
  • Valid on <body> as a window event content attribute.
  • Also assignable as window.onpagehide in script.
  • Pair with onpageshow when the page becomes visible again.
  • Use addEventListener to access event.persisted.
  • Prefer lightweight work — heavy tasks may not finish before hide.
  • Not the same as onbeforeunload (confirm dialog) or unload (legacy).

💎 Values

The onpagehide attribute accepts a string of JavaScript code:

  • onpagehide="saveDraft()" — Call a named function.
  • onpagehide="sessionStorage.setItem('draft', draft.value)" — Inline save.
  • JavaScript: window.onpagehide = (event) => { … } — property assignment.
pagehide-handler.html
function handlePageHide(event) {
  sessionStorage.setItem("draft", draftInput.value);
  if (event.persisted) {
    status.textContent = "Page cached (bfcache) — draft saved.";
  } else {
    status.textContent = "Page leaving — draft saved.";
  }
}

window.addEventListener("pagehide", handlePageHide);

⚡ Quick Reference

Property / eventWhen it firesNotes
pagehidePage is hiddenonpagehide
pageshowPage becomes visibleonpageshow
event.persistedOn pagehide / pageshowtrue = bfcache
Event targetwindowGlobal browser event
Handler attributeonpagehide on bodyWindow event handler

Applicable Elements

TargetSupported?Notes
<body>YesWindow event on body (HTML)
windowYesPrimary target in JavaScript
<div>, <button>NoUse window listeners
<frameset>Yes (legacy)Rare today
visibilitychangeRelatedTab hidden, not full navigation

onpagehide vs onpageshow vs onbeforeunload

APIWhen it firesTypical use
onpagehidePage hiddenSave draft, cleanup
onpageshowPage shownRestore UI, refresh data
onbeforeunloadBefore leaveUnsaved-changes warning
unload (legacy)Document unloadAvoid — breaks bfcache

Examples Gallery

Inline body handler, window.onpagehide assignment, and draft save with event.persisted.

👀 Live Preview

Navigate away from this page and return with Back — a timestamp is saved on pagehide:

No pagehide save yet — leave this page and come back to test.

Example — onpagehide on body

Save a draft when the page is hidden:

body-onpagehide.html
<body onpagehide="handlePageHide()">
  <textarea id="draft"></textarea>
  <p id="status"></p>
</body>

<script>
  function handlePageHide() {
    sessionStorage.setItem("draft",
      document.getElementById("draft").value);
    document.getElementById("status").textContent =
      "Draft saved on pagehide.";
  }
</script>
Try It Yourself

How It Works

The browser fires pagehide on the window when the page is hidden. The body attribute runs your handler at that moment.

Dynamic Values with JavaScript

Assign window.onpagehide dynamically:

window-onpagehide.html
<script>
  window.onpagehide = function () {
    document.getElementById("log").textContent =
      "Page is being hidden — cleanup ran.";
    sessionStorage.setItem("lastHide", Date.now());
  };
</script>
Try It Yourself

How It Works

Property assignment on window is equivalent to the inline body handler for the pagehide event.

Example — Check event.persisted (bfcache)

Handle cached vs destroyed pages differently:

pagehide-persisted.html
window.addEventListener("pagehide", function (event) {
  saveDraft();
  if (event.persisted) {
    log.textContent = "Page cached — may return via Back button.";
  } else {
    log.textContent = "Page discarded — full navigation away.";
  }
});
Try It Yourself

How It Works

event.persisted tells you whether the browser kept the page in memory. Use addEventListener — inline onpagehide cannot read the event object easily.

♿ Accessibility

  • Do not rely on pagehide for critical saves only — Also save on input blur or debounced typing.
  • Avoid blocking dialogs on leave — Use onbeforeunload sparingly; it interrupts users.
  • Preserve user work — Auto-save drafts so navigation does not lose content.
  • Announce restore on return — Use onpageshow with polite status text if data was reloaded.
  • Keep save operations fast — Slow handlers hurt navigation performance.

🧠 How onpagehide Works

1

User on page

Editing, reading.

Active
2

Navigate away

Link, close tab.

Leave
3

pagehide fires

onpagehide runs.

Event
=

Save / cleanup

Draft, analytics.

Browser Support

The pagehide event and onpagehide handler are supported in all modern browsers, including Internet Explorer 11+.

Page Lifecycle · Fully supported

Universal onpagehide support

All major browsers fire pagehide when the page is hidden from view.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 11+ supported
Full support
Opera Fully supported
Full support
onpagehide attribute 99% supported

Bottom line: Reliable for save-on-leave logic in all modern browsers.

💡 Best Practices

✅ Do

  • Pair onpagehide with onpageshow
  • Save drafts with sessionStorage or sendBeacon
  • Use addEventListener("pagehide", …) for event.persisted
  • Keep handlers fast and lightweight
  • Also auto-save while the user types

❌ Don’t

  • Use alert() on pagehide — the page is leaving
  • Confuse pagehide with full document destruction
  • Register unload handlers — they hurt bfcache
  • Run long async work without sendBeacon
  • Put onpagehide on random divs — use window

Conclusion

The onpagehide attribute runs JavaScript when the browser hides the page — ideal for saving drafts, sending analytics, and cleaning up before navigation.

Pair it with onpageshow, read event.persisted with addEventListener, and avoid legacy unload handlers that break bfcache.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onpagehide

Bookmark these before wiring page lifecycle handlers.

5
Core concepts
🔄 02

+ onpageshow

Pair both.

Pattern
🔎 03

.persisted

bfcache.

API
💾 04

Save drafts

On leave.

UX
05

Not unload

Page cached.

Gotcha

❓ Frequently Asked Questions

It runs JavaScript when the pagehide event fires — when the browser hides the page during navigation or tab close.
No. pagehide is modern and bfcache-friendly. The legacy unload event can prevent back-forward caching — prefer pagehide.
true when the page enters the back-forward cache instead of being destroyed — common when using the Back button.
Click a link to leave the page, close the tab, or navigate away — then use Back. Save to sessionStorage to verify the handler ran.
window.addEventListener("pagehide", handler) is preferred — you need it to read event.persisted.
Yes in all modern browsers; Internet Explorer 11+.

Save work before users leave

Practice the onpagehide attribute with draft-saving examples in the Try It editor.

Try onpagehide demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful