Browser refresh using OnBeforeUnload event

有些话、适合烂在心里 提交于 2019-12-04 10:42:55
vernonner3voltazim

So far as I know, you can't actually test for the browser being closed; you can only test for a window (or tab) being closed. That generally suffices, unless of course a page-refresh happens, since it counts as both closing and re-opening a web page inside a window or tab. What is needed is an event-handler for a click on the browser's page-refresh button, but I'm not sure such exists. Here is something:

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

and also

Handling Browser close event and Page Refresh

One thing I've encountered in trying to find something about a page-refresh event-handler is the notion of using "local storage". You could, as part of the on-before-unload handler, put a small data item, time-stamped, into local storage. Activate a kind of timer on the Server, and wait for that time to expire before erasing the session. When your page is loaded, test local storage for that data item. If it exists and the time-stamp was very recent, you know the page was refreshed and can can do appropriate things based on knowing that --like sending an AJAX message to the Server telling it to not erase the session just yet.

To better manage a session and work around user pressing a browser refresh, you need to

  • Remove the logout functionality when the window is closed.
  • Implement InActivity monitor on the client and the server which will clear the session if the user is inactive for certain time. So if the user closes the browser, the session in MongoDB will persist for some time, till the server clears it.
  • Implement keepalive pings from the client to the server which will ping the server every set time interval if the user is active on the page. To reduce network traffic, you can reschedule keepalive, whenever the server is invoked either using AJAX or RESTful api.
  • Save the user session in the browser in local storage so the session can be re-read in case of browser refresh.

This InActivity monitor can be a good starting point. https://github.com/HackedByChinese/ng-idle/blob/develop/src/angular-idle.js. I have done all the above in my angular project. Hope that helps.

As Alex suggested, you can use session Cookies to check if your website has been seen for the current session (IE7+ support).

Example

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

var isRefresh = true;
var sessionAlive = readCookie("sessionAlive");
if (sessionAlive === null) {
    isRefresh = false;
    sessionStorage.setItem("sessionAlive", true);
}

var windowsCloseEventListener = window.attachEvent || window.addEventListener;
var chkForBrowserCloseEvents = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
windowsCloseEventListener(chkForBrowserCloseEvents, function (e) {
    if (!isRefresh) {
        $scope.logout();
    }
});

You can use sessionStorage, which is more of the HTML5 way, to see if the browser has been closed (new session) (IE8+ support).

Example:

var isRefresh = true;
var sessionAlive = sessionStorage.getItem("sessionAlive");
if (sessionAlive === null) {
    isRefresh = false;
    sessionStorage.setItem("sessionAlive", true);
}

var windowsCloseEventListener = window.attachEvent || window.addEventListener;
var chkForBrowserCloseEvents = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
windowsCloseEventListener(chkForBrowserCloseEvents, function (e) {
    if (!isRefresh) {
        $scope.logout();
    }
});

readCookie taken from: http://www.quirksmode.org/js/cookies.html

Use cookie with session expire should work.

WindowEventHandlers.onbeforeunload

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

this example shows that the addEventListener and attachEvent methods cannot be used for the onbeforeunload event (except in Google Chrome and Safari):

 if (window.addEventListener) {  // all browsers except IE before version 9
            window.addEventListener ("beforeunload", OnBeforeUnLoad, false);
        }
        else {
            if (window.attachEvent) {   // IE before version 9
                window.attachEvent ("onbeforeunload", OnBeforeUnLoad);
            }
        }

            // the OnBeforeUnLoad method will only be called in Google Chrome and Safari
        function OnBeforeUnLoad () {
            return "All data that you have entered will be lost!";
        }

you can use "onbeforeunload " event to handle this situation.

$wnd.onbeforeunload = function(e) {

        var logoutClicked = callSomeFunctionToGetIfLogoutButtonIsClicked();
        if (!logoutClicked) {
            return "Some message";
        }
        return;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!