使用javascript处理刷新页面事件

tib*_*boo 20 javascript javascript-events

是否可以使用javascript来处理刷新页面的事件?我想要的是,如果用户执行以下行为之一,请注意:

  • 按F5刷新页面
  • 关闭标签或浏览器
  • 输入新网址,然后按浏览器上的Enter键

显示警告信息?
提前致谢!

Lou*_*nco 28

你不想刷新,你想要onbeforeunload事件.

http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

文章的示例代码

<HTML>
<head>
<script>
function closeIt()
{
  return "Any string value here forces a dialog box to \n" + 
         "appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
  <a href="http://www.microsoft.com">Click here to navigate to 
      www.microsoft.com</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 现在为最新版本的 chrome 工作:) (2认同)

Dar*_*rov 6

最接近的是window.onbeforeunload事件:

window.onbeforeunload = function (e) {
    var e = e || window.event;

    // For IE and Firefox
    if (e) {
        e.returnValue = 'Leaving the page';
    }

    // For Safari
    return 'Leaving the page';
};
Run Code Online (Sandbox Code Playgroud)

需要注意的是,您需要从此函数返回一个字符串,这一点很重要。