can i be notified of cookie changes in client side javascript

后端 未结 6 1146
梦毁少年i
梦毁少年i 2020-12-03 01:21

Can I somehow follow changes to cookies (for my domain) in my client side javascript. For example a function that gets called if a cookie gets changed , deleted or added

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 01:47

    If the code that manipulated the cookies is yours, you can use localStorage for tracking changed with events. for example, you can store a junk on the localStorage to trigger an event on the other tabs.

    for example

    var checkCookie = function() {
    
    var lastCookies = document.cookie.split( ';' ).map( function( x ) { return x.trim().split( /(=)/ ); } ).reduce( function( a, b ) { 
            a[ b[ 0 ] ] = a[ b[ 0 ] ] ? a[ b[ 0 ] ] + ', ' + b.slice( 2 ).join( '' ) :  
            b.slice( 2 ).join( '' ); return a; }, {} );
    
    
    return function() {
    
        var currentCookies =  document.cookie.split( ';' ).map( function( x ) { return x.trim().split( /(=)/ ); } ).reduce( function( a, b ) { 
            a[ b[ 0 ] ] = a[ b[ 0 ] ] ? a[ b[ 0 ] ] + ', ' + b.slice( 2 ).join( '' ) :  
            b.slice( 2 ).join( '' ); return a; }, {} );
    
    
        for(cookie in currentCookies) {
            if  ( currentCookies[cookie] != lastCookies[cookie] ) {
                console.log("--------")
                console.log(cookie+"="+lastCookies[cookie])
                console.log(cookie+"="+currentCookies[cookie])
            }
    
        }
        lastCookies = currentCookies;
    
    };
    }();
     $(window).on("storage",checkCookie); // via jQuery. can be used also with VanillaJS
    
    
    // on the function changed the cookies
    
    document.cookie = ....
    window.localStorage["1"] = new Date().getTime(); // this will trigger the "storage" event in the other tabs.
    

提交回复
热议问题