Handle Refresh Page Event with Javascript

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?

0

2 Answers

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

(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="">Click here to navigate to 
      
</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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest