ตัวอย่างโค้ดด้านล่าง เป็นการประยุกต์ใช้ event ชื่อ beforeunload สำหรับการแจ้งเตือนการปิด บราวเซอร์ โดยเมื่อทำการยืนยันการปิดบราวเซอร์ แล้วให้สามารถไปทำงานในส่วน เรียกใช้ ajax หรือฟังก์ชันที่ต้องการก่อนปิด ได้ (ทดสอบกับ IE Firefox Chrome เวอร์ล่าสุดใช้งานได้)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <!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> </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> </div> <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 เพื่อให้มีการเปลี่บนแปลงในหน้าเพจ ก่อน แล้วปิดหน้าเว็บเพจนี้