27

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tiboo
  • 8,213
  • 6
  • 33
  • 43

2 Answers2

32

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>
Lou Franco
  • 87,846
  • 14
  • 132
  • 192
7

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I'm pretty sure that you don't need to do anything with `e.returnValue` for IE/FF. You just need to return a string. – Matt Ball Oct 16 '10 at 22:08
  • @MattBall - it's referring to IE < 8 and Firefox prior to version 4. see [the docs on MDN](https://developer.mozilla.org/en/DOM/window.onbeforeunload). – Eliran Malka Jun 03 '12 at 13:58