Javascript如何監(jiān)聽頁面刷新和關(guān)閉事件
在我們的日常生活中,時常遇到這么一種情況,當(dāng)我們在點擊一個鏈接、關(guān)閉頁面、表單提交時等情況,會提示我們是否確認(rèn)該操作等信息。
這里就給大家講講javascript的onbeforeunload()和onunload()兩個事件。
相同點:
兩者都是在對頁面的關(guān)閉或刷新事件作個操作。
不同點:
unbeforeunload()事件執(zhí)行的順序在onunload()事件之前發(fā)生。(因為,unbeforeunload()是在頁面刷新之前觸發(fā)的事件,而onubload()是在頁面關(guān)閉之后才會觸發(fā)的)。
unbeforeunload()事件可以禁止onunload()事件的觸發(fā)。
onunload()事件是無法阻止頁面關(guān)閉的。
瀏覽器的兼容
onunload:
IE6,IE7,IE8 中 刷新頁面、關(guān)閉瀏覽器之后、頁面跳轉(zhuǎn)之后都會執(zhí)行;
IE9 刷新頁面 會執(zhí)行,頁面跳轉(zhuǎn)、關(guān)閉瀏覽器不能執(zhí)行;
firefox(包括firefox3.6) 關(guān)閉標(biāo)簽之后、頁面跳轉(zhuǎn)之后、刷新頁面之后能執(zhí)行,但關(guān)閉瀏覽器不能執(zhí)行;
Safari 刷新頁面、頁面跳轉(zhuǎn)之后會執(zhí)行,但關(guān)閉瀏覽器不能執(zhí)行;
Opera、Chrome 任何情況都不執(zhí)行。
onbeforeunload:
IE、Chrome、Safari ***支持
Firefox 不支持文字提醒信息
Opera 不支持
IE6,IE7會出現(xiàn)bug
示例代碼:
onbeforeunload():
方式一:html元素中添加
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title></title>
- </head>
- <body onbeforeunload="return myFunction()">
- <p>該實例演示了如何向 body 元素添加 "onbeforeunload" 事件。</p>
- <p>關(guān)閉當(dāng)前窗口,按下 F5 或點擊以下鏈接觸發(fā) onbeforeunload 事件。</p>
- <a href="http://www.qqtimezone.top">博客地址</a>
- <script>
- function myFunction() {
- return "自定義內(nèi)容";
- }
- </script>
- </body>
- </html>
方式二:javascript中添加
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>菜鳥教程(runoob.com)</title>
- </head>
- <body>
- <p>該實例演示了如何使用 HTML DOM 向 body 元素添加 "onbeforeunload" 事件。</p>
- <p>關(guān)閉當(dāng)前窗口,按下 F5 或點擊以下鏈接觸發(fā) onbeforeunload 事件。</p>
- <a href="http://www.runoob.com">點擊調(diào)整到菜鳥教程</a>
- <script>
- window.onbeforeunload = function(event) {
- event.returnValue = "我在這寫點東西...";
- };
- </script>
- </body>
- </html>
方式三:添加addEventListener()事件(不過此方法IE8以下不支持)
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title></title>
- </head>
- <body>
- <p>該實例演示了如何使用 addEventListener() 方法向 body 元素添加 "onbeforeunload" 事件。</p>
- <p>關(guān)閉當(dāng)前窗口,按下 F5 或點擊以下鏈接觸發(fā) onbeforeunload 事件。</p>
- <a href="http://www.qqtimezone.top">跳轉(zhuǎn)地址</a>
- <script>
- window.addEventListener("beforeunload", function(event) {
- event.returnValue = "我在這寫點東西...";
- });
- </script>
- </body>
- </html>
onunload():
方式一:html元素中添加
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <script type="text/javascript">
- function fun() {
- // dosomethings
- }
- </script>
- </head>
- <body onunload="fun()">
- </body>
- </html>
方式二:javascript添加
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <script type="text/javascript">
- window.onunload = function() {
- // dosomethings
- };
- </script>
- </head>
- <body>
- </body>
- </html>
【本文為51CTO專欄作者“太平洋警察”的原創(chuàng)稿件,轉(zhuǎn)載請通過作者獲取授權(quán)】