Which Script Set That Cookie?
How to link a script loaded on your page to cookie in Chrome's DevTools
Overview
Reading a vendor's cookie can sometimes grant access to data they don't directly provide. However, cookie names usually don't offer sufficient information to trace them back to the scripts responsible for their creation. As a result, we often find ourselves regularly reading cookie values for CMPs and other marketing tags.
Here's a quick way to find out which script set that cookie:
- Add a breakpoint to the first javascript you see loaded on the page in your Chrome DevTools.
- Reload the page with DevTools open and you should find yourself paused in the debugger.
- While paused, copy and paste the following code into the console.
(()=> {
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) {
debugger;
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
}));
};
})();
Updated 6 months ago