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



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Darin Dimitrov