Logout all open tabs automatically when user logs out in one of them

空扰寡人 提交于 2019-12-17 10:49:38

问题


I have created Login page, based on localStorage. On loading the page I have checked the value of localStorage. If I opened the web page in more than one tab and then I logout from any one of the tabs, all the remaining pages should logout automatically.

If reload/refresh means it logging out.

Please help me to run a script, when user view the page or say any other way to solve this problem.


回答1:


You can use Storage events to be notified when localStorage values are changed.

function storageChange (event) {
    if(event.key === 'logged_in') {
        alert('Logged in: ' + event.newValue)
    }
}
window.addEventListener('storage', storageChange, false)

If, for example, one of the tabs logs out:

window.localStorage.setItem('logged_in', false)

Then all other tabs will receive a StorageEvent, and an alert will appear:

Logged in: false

I hope this answers your question!




回答2:


"localStorage persists any saved data indefinitely on the user's computer and across browser tabs" Source

This means that if you empty / remove the login data you've set in one tab, the data will be changed in all other tabs as well.

So, if the user logs out, localStorage data changes.
Then, on your tabs, detect when a user changes focus to that tab again using the onfocus event:

function onFocus(){
//Reload Page if logged out (Check localStorage)
    window.location.reload();
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.addEventHandler("focusin", onFocus);
} else {
    window.addEventHandler("focus", onFocus);
}

Source

This means you won't be constantly running javascript, or reloading (a possibly large amount of) tabs at the same time.




回答3:


This can also be done with an HTTP header if you are able to set one either in Apache or from a server-side script like PHP:

Clear-Site-Data: "cookies", "storage", "executionContexts"

E.g. in PHP:

header('Clear-Site-Data: "cookies", "storage", "executionContexts"');

The key thing to note here is the "executionContexts" directive. From the doc:

"executionContexts"

Indicates that the server wishes to reload all browsing contexts for the origin of the response (Location.reload).

The compatibility in certain browsers (ahem..IE/Edge) is unknown at this time but there is support for this header in most good browsers.




回答4:


Have a look at Page Visibility API for HTML5. This can help you out



来源:https://stackoverflow.com/questions/13513874/logout-all-open-tabs-automatically-when-user-logs-out-in-one-of-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!