27

Using the following function is it possible to detect which button the user has pressed the refresh button or the close button? If not is there another way?

$(window).bind('beforeunload', function(event) {
    return 'pls save ur work';
});
Ram
  • 3,092
  • 10
  • 40
  • 56
Ryder
  • 281
  • 1
  • 4
  • 5

1 Answers1

21

The simple answer is no - browsers' security models do not allow you to explicitly detect in what way a user has chosen to leave your page (refresh / close / internal link / external link).

detect refresh browser for unload/beforeunload when browser closed

It is possible - using a cookie - to check when a user loads your page whether they were previously on that site in the same session - e.g. detect if they have refreshed - but not before they refresh:

Detect Browser Refresh in Javascript

Check if page gets reloaded or refreshed in Javascript

A partial and imperfect approach would be to detect whether they pressed "F5" or "Ctrl+R" or "Cmd+R" (keyboard shortcuts for refresh) just before the page unload. This will detect some refreshes, but not where the user actually clicked the refresh button.

(function($) {
    var refreshKeyPressed = false;
    var modifierPressed = false;

    var f5key = 116;
    var rkey = 82;
    var modkey = [17, 224, 91, 93];

    // Check for refresh keys
    $(document).bind(
        'keydown',
        function(evt) {
            // Check for refresh
            if (evt.which == f5key || window.modifierPressed && evt.which == rkey) {
                refreshKeyPressed = true;
            }

            // Check for modifier
            if (modkey.indexOf(evt.which) >= 0) {
                modifierPressed = true;
            }
        }
    );

    // Check for refresh keys
    $(document).bind(
        'keyup',
        function(evt) {
            // Check undo keys
            if (evt.which == f5key || evt.which == rkey) {
                refreshKeyPressed = false;
            }

            // Check for modifier
            if (modkey.indexOf(evt.which) >= 0) {
                modifierPressed = false;
            }
        }
    );

    $(window).bind('beforeunload', function(event) {
        var message = "not refreshed";

        if (refreshKeyPressed) {
            message = "refreshed";
        }

        event.returnValue = message;
        return message;
    });
}(jQuery));

You can also detect when a link is clicked whether the target of the link is on the same site or not: How can I detect when the user is leaving my site, not just going to a different page?

Community
  • 1
  • 1
Robin Winslow
  • 10,908
  • 8
  • 62
  • 91