Handle page refresh event with javascript

Can I use javascript to handle the page refresh event? I want to be notified if the user takes one of these actions:

  • refresh the page by pressing F5
  • close tab or browser
  • enter new url and hit enter button browser

to display a warning message?
Thanks in advance!

+13


source to share


2 answers


You don't want to update, 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>

      

+23


source


The closest you can 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's important to note that you need to return a string from this function.

+4


source







All Articles