Handle refresh page event with javascript

谁说胖子不能爱 提交于 2019-12-17 15:44:18

问题


Is it possible to use javascript to handle the event of refreshing page? What i want is get notice if user do one of these behaviours:

  • refresh page by pressing F5
  • close tab or browser
  • enter a new url then press enter on browser

to display a warning message?
Thanks in advance!


回答1:


You don't want the refresh, you want the onbeforeunload event.

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

Sample code from article

<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>



回答2:


The closest you could get is the window.onbeforeunload event:

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';
};

It is important to note that you need to return a string from this function.



来源:https://stackoverflow.com/questions/3950029/handle-refresh-page-event-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!