Event onpagehide ทริกเกอร์เมื่อ ผู้ใช้ออกจากหน้า เช่น คลิกลิงก์ กด Back/Forward รีเฟรช ปิด Tab — รองรับ Back-Forward Cache (bfcache)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body onpagehide="newFunc()">
<p>Close the page and see what happens!</p>
<script>
function newFunc() {
alert("Thank you!");
}
</script>
</body>
</html>
คำอธิบาย
- ทริกเกอร์เมื่อหน้าถูก Unload และ เมื่อหน้าถูก Cache ไว้ใน bfcache (Page Hide)
- Event Object มี Property
persisted:true= หน้าอยู่ใน bfcache (ยังมีชีวิต),false= หน้าจะถูกทำลายจริง - ทันสมัยกว่า
onunloadและไม่บล็อก bfcache
ตัวอย่างใช้ persisted
window.addEventListener('pagehide', (e) => {
if (e.persisted) {
console.log('Page cached in bfcache - may restore instantly');
} else {
console.log('Page truly unloading - cleanup here');
navigator.sendBeacon('/logout', 'cleanup');
}
});
เปรียบเทียบ Events ท้ายหน้า
| Event | ทริกเกอร์เมื่อ | bfcache | Async |
|---|---|---|---|
beforeunload | ก่อน Unload (Cancel ได้) | บล็อก bfcache | ไม่ได้ |
pagehide | หน้าถูกซ่อน/Unload | รองรับ (persisted) | ไม่ได้ |
unload | หน้าถูกทำลาย | บล็อก bfcache | ไม่ได้ |
visibilitychange | Tab ซ่อน/แสดง | ไม่เกี่ยว | ได้ |
แนะนำ: ใช้ pagehide + navigator.sendBeacon() สำหรับ Analytics/Cleanup ที่น่าเชื่อถือที่สุด