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

前端 未结 4 1276
日久生厌
日久生厌 2020-12-01 09:31

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 logo

相关标签:
4条回答
  • 2020-12-01 09:48

    "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.

    0 讨论(0)
  • 2020-12-01 10:05

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

    0 讨论(0)
  • 2020-12-01 10:07

    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.

    0 讨论(0)
  • 2020-12-01 10:10

    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!

    0 讨论(0)
提交回复
热议问题