简体   繁体   English

使用OnBeforeUnload事件刷新浏览器

[英]Browser refresh using OnBeforeUnload event

On the web page when the user clicks on the logout button, I have a JavaScript function which clears the user session which is stored on the MongoDB. 在用户点击注销按钮的网页上,我有一个JavaScript函数,用于清除存储在MongoDB上的用户会话。 It works fine. 它工作正常。

Also I would like to clear the user session when the user closes the browser. 此外,我想在用户关闭浏览器时清除用户会话。 Here is the issue I am facing : when the user clicks on the refresh icon the logout function is getting called. 这是我面临的问题:当用户点击刷新图标时,将调用注销功能。 I only want this function to be called when the browser is closed. 我只希望在浏览器关闭时调用此函数。

Can I prevent this function from calling on the page refresh? 我可以阻止此功能调用页面刷新吗?

My logic here is to clean up the session when the browser is closed. 我的逻辑是在浏览器关闭时清理会话。 I am deleting the session which is on MongoDB. 我正在删除MongoDB上的会话。 Is there a better way to manage the session? 有没有更好的方法来管理会话?

var isRefresh = false;
$(window).keydown(function (event) {
    if (event.keyCode == 116) { // User presses F5 to refresh
        refresh = true;
    }
});

// Calls the logout function when you close the browser thus cleans the session data.
var windowsCloseEventListener = window.attachEvent || window.addEventListener;
var chkForBrowserCloseEvents = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
windowsCloseEventListener(chkForBrowserCloseEvents, function (e) { // For >=IE7, Chrome, Firefox
    if (!isRefresh) {
        $scope.logout();
    }
});

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. 作为on-before-unload处理程序的一部分,您可以将带有时间戳的小数据项放入本地存储中。 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. 如果它存在并且时间戳是最近的,你知道页面被刷新并且可以基于知道 - 例如向服务器发送AJAX消息告诉它还没有擦除会话来做适当的事情。

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. 在客户端和服务器上实施InActivity监视器,如果用户在特定时间内处于非活动状态,则会清除会话。 So if the user closes the browser, the session in MongoDB will persist for some time, till the server clears it. 因此,如果用户关闭浏览器,MongoDB中的会话将持续一段时间,直到服务器清除它。
  • 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. 实现从客户端到服务器的keepalive ping,如果用户在页面上处于活动状态,则服务器将在每个设置的时间间隔内ping服务器。 To reduce network traffic, you can reschedule keepalive, whenever the server is invoked either using AJAX or RESTful api. 为了减少网络流量,只要使用AJAX或RESTful api调用服务器,就可以重新安排keepalive。
  • 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. 此InActivity监视器可以是一个很好的起点。 https://github.com/HackedByChinese/ng-idle/blob/develop/src/angular-idle.js . 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). 正如Alex建议的那样,您可以使用会话Cookie来检查您的网站是否已在当前会话中看到(IE7 +支持)。

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). 您可以使用更多HTML5方式的sessionStorage来查看浏览器是否已关闭(新会话)(IE8 +支持)。

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 readCookie取自: http ://www.quirksmode.org/js/cookies.html

使用会话过期的cookie应该有效。

WindowEventHandlers.onbeforeunload 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): 此示例显示addEventListener和attachEvent方法不能用于onbeforeunload事件(Google Chrome和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. 你可以使用“onbeforeunload”事件来处理这种情况。

$wnd.onbeforeunload = function(e) {

        var logoutClicked = callSomeFunctionToGetIfLogoutButtonIsClicked();
        if (!logoutClicked) {
            return "Some message";
        }
        return;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 防止在浏览器中向后导航,但不阻止使用window.onbeforeunload刷新 - Prevent back navigation in browser, but not prevent refresh using window.onbeforeunload 在onbeforeunload()事件中使用Confirm() - Using Confirm() in onbeforeunload() event 我需要在浏览器关闭时弹出确认窗口。我正在使用onbeforeunload事件,但无法在Firefox中使用,并且还希望限制页面刷新时的弹出窗口 - I need a confirmation pop up on browser close.I am using onbeforeunload event but not working in Firefox also want to restrict pop up on page refresh 标签页(或浏览器)关闭时的Chrome onbeforeunload事件 - Chrome onbeforeunload event when tab (or browser) closes 没有onbeforeunload和unload事件的浏览器后退事件 - Browser Back Event without onbeforeunload and unload events 如何使用javascript捕获浏览器刷新事件 - How to capture browser refresh event using javascript 如何取消对javascript函数调用和页面刷新的onbeforeunload事件的绑定 - how to unbind onbeforeunload event on javascript function call and page refresh 防止在刷新/ F5中发生OnBeforeUnload()事件 - prevent OnBeforeUnload() event from happening in refresh/F5 刷新或返回时将触发onb​​eforeunload事件,但注销时不触发 - onbeforeunload event to be fired when refresh or back but not when log out 无法使用 Angular 服务处理 onbeforeunload 事件 - Unable to handle onbeforeunload event using Angular Service
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM