javascript如何监听页面刷新和页面关闭事件

时间:2023-03-09 05:57:00
javascript如何监听页面刷新和页面关闭事件

2017-03-07

在我们的日常生活中,时常遇到这么一种情况,当我们在点击一个链接、关闭页面、表单提交时等情况,会提示我们是否确认该操作等信息。

这里就给大家讲讲javascript的onbeforeunload()和onunload()两个事件。

相同点:

两者都是在对页面的关闭或刷新事件作个操作。

不同点:

  1. unbeforeunload()事件执行的顺序在onunload()事件之前发生。(因为,unbeforeunload()是在页面刷新之前触发的事件,而onubload()是在页面关闭之后才会触发的)。
  2. unbeforeunload()事件可以禁止onunload()事件的触发。
  3. onunload()事件是无法阻止页面关闭的。
  4. 浏览器的兼容
  • onunload:

  • IE6,IE7,IE8 中 刷新页面、关闭浏览器之后、页面跳转之后都会执行;

  • IE9 刷新页面 会执行,页面跳转、关闭浏览器不能执行;

  • firefox(包括firefox3.6) 关闭标签之后、页面跳转之后、刷新页面之后能执行,但关闭浏览器不能执行;

  • Safari 刷新页面、页面跳转之后会执行,但关闭浏览器不能执行;

  • Opera、Chrome 任何情况都不执行。

    javascript如何监听页面刷新和页面关闭事件

  • onbeforeunload:
  • IE、Chrome、Safari 完美支持

  • Firefox 不支持文字提醒信息

  • Opera 不支持

  • IE6,IE7会出现bug

  javascript如何监听页面刷新和页面关闭事件

示例代码:

onbeforeunload():

方式一:html元素中添加

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body onbeforeunload="return myFunction()"> <p>该实例演示了如何向 body 元素添加 "onbeforeunload" 事件。</p>
<p>关闭当前窗口,按下 F5 或点击以下链接触发 onbeforeunload 事件。</p>
<a href="http://www.qqtimezone.top">博客地址</a>
<script>
function myFunction() {
return "自定义内容";
}
</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>关闭当前窗口,按下 F5 或点击以下链接触发 onbeforeunload 事件。</p>
<a href="http://www.runoob.com">点击调整到菜鸟教程</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>关闭当前窗口,按下 F5 或点击以下链接触发 onbeforeunload 事件。</p>
<a href="http://www.qqtimezone.top">跳转地址</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>