ตัวอย่างโค้ดด้านล่าง เป็นการประยุกต์ใช้ event ชื่อ beforeunload สำหรับการแจ้งเตือนการปิด บราวเซอร์ โดยเมื่อทำการยืนยันการปิดบราวเซอร์ แล้วให้สามารถไปทำงานในส่วน เรียกใช้ ajax หรือฟังก์ชันที่ต้องการก่อนปิด ได้ (ทดสอบกับ IE Firefox Chrome เวอร์ล่าสุดใช้งานได้)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Document</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" >
</head>
<body>
<div style="margin:auto; width:500px;">
<form name="form1" method="post" action="">
<div>Message: </div>
<div>
<input type="text" name="mytext" class="mycss enter_key_not_allow">
</div>
<div>
<textarea name="msg" cols="50" rows="3" id="msg"></textarea>
</div>
<div>
<br>
<button type="submit" id="btn_submit" name="btn_submit" >Send Message</button>
</div>
</form><br>
<a href="http://www.ebiwayo.com">Ebiwayo</a>
</div>
<script src="https://unpkg.com/[email protected]/dist/jquery.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function(){
$(window).bind("beforeunload",function(event){
var msg="ยืนยันการปิดหน้านี้?";
event.preventDefault();
$(window).bind("unload",function(event){
event.stopImmediatePropagation();
// แทรก ajax code ลบ session หรืออื่น ๆ
alert("Bye Bye");
});
return msg;
});
$("a").click(function(){ // กรณีคลิกลิ้งค์ ไม่ต้องแสดง การแจ้งเตือน
$(window).unbind("beforeunload");
});
});
</script>
</body>
</html>
ตัวอย่าง ข้อยกเว้นกรณีลิ้งค์ Ebiwayo
ทดสอบด้วยการ กรอกข้อมูลใน Textbox เพื่อให้มีการเปลี่บนแปลงในหน้าเพจ ก่อน แล้วปิดหน้าเว็บเพจนี้