Which Script Set That Cookie?
How to link a script loaded on your page to cookie in Chrome's DevTools
Sometimes reading a vendors cookie allows data access they don't provide directly. However, cookie names don't typically provide enough information to link them back to the scripts that create them. We find ourselves reading cookie values for CMPs, and other marketing tags on a regular basis.
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
}));
};
})();
You can now click continue on the debugger, and step through each cookie that's set.
Updated about 1 month ago