Reputation: 359
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.
Upvotes: 30
Views: 24243
Reputation: 9846
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.
Upvotes: 1
Reputation: 2552
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!
Upvotes: 56
Reputation: 72857
"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);
}
This means you won't be constantly running javascript, or reloading (a possibly large amount of) tabs at the same time.
Upvotes: 6
Reputation: 12683
Have a look at Page Visibility API for HTML5. This can help you out
Upvotes: 0