Handle refresh page event with javascript

后端 未结 2 1009
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 01:15

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
相关标签:
2条回答
  • 2020-12-03 01:58

    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.

    0 讨论(0)
  • 2020-12-03 02:02

    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>
    
    0 讨论(0)
提交回复
热议问题