我可以在客户端javascript中以某种方式跟踪对cookies(对于我的域)的更改吗?例如,如果 cookie 被更改、删除或添加时调用的函数
按优先顺序
- 标准跨浏览器
- 跨浏览器
- 特定浏览器
- 扩展/插件
为什么?因为我在窗口/选项卡#1中依赖的cookie可以在窗口/选项卡#2中更改。
我发现 chrome 允许在 cookie 更改时通知扩展。但那是我最不喜欢的选择
我可以在客户端javascript中以某种方式跟踪对cookies(对于我的域)的更改吗?例如,如果 cookie 被更改、删除或添加时调用的函数
按优先顺序
为什么?因为我在窗口/选项卡#1中依赖的cookie可以在窗口/选项卡#2中更改。
我发现 chrome 允许在 cookie 更改时通知扩展。但那是我最不喜欢的选择
一种选择是编写一个定期检查 cookie 是否有更改的函数:
var checkCookie = function() {
var lastCookie = document.cookie; // 'static' memory between function calls
return function() {
var currentCookie = document.cookie;
if (currentCookie != lastCookie) {
// something useful like parse cookie, run a callback fn, etc.
lastCookie = currentCookie; // store latest cookie
}
};
}();
window.setInterval(checkCookie, 100); // run every 100 ms
方法 1:定期轮询
轮询document.cookie
function listenCookieChange(callback, interval = 1000) {
let lastCookie = document.cookie;
setInterval(()=> {
let cookie = document.cookie;
if (cookie !== lastCookie) {
try {
callback({oldValue: lastCookie, newValue: cookie});
} finally {
lastCookie = cookie;
}
}
}, interval);
}
用法
listenCookieChange(({oldValue, newValue})=> {
console.log(`Cookie changed from "${oldValue}" to "${newValue}"`);
}, 1000);
document.cookie = 'a=1';
方法二:API拦截
截距document.cookie
(()=> {
let lastCookie = document.cookie;
// rename document.cookie to document._cookie, and redefine document.cookie
const expando = '_cookie';
let nativeCookieDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
Object.defineProperty(Document.prototype, expando, nativeCookieDesc);
Object.defineProperty(Document.prototype, 'cookie', {
enumerable: true,
configurable: true,
get() {
return this[expando];
},
set(value) {
this[expando] = value;
// check cookie change
let cookie = this[expando];
if (cookie !== lastCookie) {
try {
// dispatch cookie-change messages to other same-origin tabs/frames
let detail = {oldValue: lastCookie, newValue: cookie};
this.dispatchEvent(new CustomEvent('cookiechange', {
detail: detail
}));
channel.postMessage(detail);
} finally {
lastCookie = cookie;
}
}
}
});
// listen cookie-change messages from other same-origin tabs/frames
const channel = new BroadcastChannel('cookie-channel');
channel.onmessage = (e)=> {
lastCookie = e.data.newValue;
document.dispatchEvent(new CustomEvent('cookiechange', {
detail: e.data
}));
};
})();
用法
document.addEventListener('cookiechange', ({detail: {oldValue, newValue}})=> {
console.log(`Cookie changed from "${oldValue}" to "${newValue}"`);
});
document.cookie = 'a=1';
笔记
| Metric \ Method | Periodic Polling | API Interception |
| ---------------- | --------------------------- | ---------------- |
| delay | depends on polling interval | instant |
| scope | same-domain | same-origin |
我觉得我的方法更好。我编写了一个自定义事件来检测 cookie 何时出现:
const cookieEvent = new CustomEvent("cookieChanged", {
bubbles: true,
detail: {
cookieValue: document.cookie,
checkChange: () => {
if (cookieEvent.detail.cookieValue != document.cookie) {
cookieEvent.detail.cookieValue = document.cookie;
return 1;
} else {
return 0;
}
},
listenCheckChange: () => {
setInterval(function () {
if (cookieEvent.detail.checkChange() == 1) {
cookieEvent.detail.changed = true;
//fire the event
cookieEvent.target.dispatchEvent(cookieEvent);
} else {
cookieEvent.detail.changed = false;
}
}, 1000);
},
changed: false
}
});
/*FIRE cookieEvent EVENT WHEN THE PAGE IS LOADED TO
CHECK IF USER CHANGED THE COOKIE VALUE */
document.addEventListener("DOMContentLoaded", function (e) {
e.target.dispatchEvent(cookieEvent);
});
document.addEventListener("cookieChanged", function (e) {
e.detail.listenCheckChange();
if(e.detail.changed === true ){
/*YOUR CODE HERE FOR DO SOMETHING
WHEN USER CHANGED THE COOKIE VALUE */
}
});
如果操作 cookie 的代码是您的,您可以使用 localStorage
事件跟踪更改。例如,您可以在 localStorage 上存储垃圾以触发其他选项卡上的事件。
例如
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.
略微改进(显示每个更改的 cookie 的 console.log):
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.setInterval(checkCookie, 100);
我们可以使用CookieStore
API:
cookieStore.addEventListener('change', ({changed}) => {
for (const {name, value} of changed) {
console.log(`${name} was set to ${value}`);
}
});
如果你想使用新的CookieStore并希望得到所有浏览器的支持,你可以安装一个(推测的)polyfill,如下所示:https ://github.com/markcellus/cookie-store