Skip to content

Instantly share code, notes, and snippets.

@cunneen
Last active February 13, 2025 08:03
Show Gist options
  • Save cunneen/f543f1c9c57d7649e3df0fb941739d43 to your computer and use it in GitHub Desktop.
Save cunneen/f543f1c9c57d7649e3df0fb941739d43 to your computer and use it in GitHub Desktop.
Export a website's cookies as JSON
window.confirm("Copy Cookies?") &&
(() => {
// modal (popup) div
const div = document.createElement("div");
div.setAttribute("style", "margin: auto; width: 25%; min-height: 25%; position: absolute; top: 25%; bottom: 25%; left: 25%; right: 25%; background-color: #ffe; padding: 1em; z-index:99999; border: 2px solid blue; border-radius: 1em; box-shadow: 4px 4px 8px #aaa;");
// document.cookies keys and values as JSON text
const cookiesJSONText = JSON.stringify(
Object.fromEntries(
document.cookie.split(/; ?/)
.map(c => c.split("="))
), null, 2);
// cookies as JS code that can be pasted into another browser
const code = `Object.entries(${cookiesJSONText}).forEach(([k,v])=>{document.cookie=k + '=' + v;});`;
const label = document.createElement("label");
label.setAttribute("for", "cookiesTA");
label.innerText = "Cookies as JSON:"
label.setAttribute("style", "display: block;")
div.appendChild(label)
// a textarea containing our cookies as JSON
const el = document.createElement("textarea");
el.setAttribute("id", "cookiesTA");
el.value = cookiesJSONText;
el.setAttribute("readonly", "");
el.setAttribute("style", "height: 75%; margin: 1em; display: block;")
div.appendChild(el);
const btnStyle = "padding: 0.5em; border: 1px solid #999; border-radius: 1em; display: inline-block; margin: 0.5em;";
// "copy json" button
const btn = document.createElement("button");
btn.setAttribute("style", btnStyle);
btn.innerText = "Copy JSON";
btn.addEventListener("click", () => {
el.select();
document.execCommand("copy");
document.body.removeChild(div);
alert("Cookies Copied!");
})
div.appendChild(btn);
// "copy code" button
const btnCode = document.createElement("button");
btnCode.setAttribute("style", btnStyle);
btnCode.innerText = "Copy Code";
btnCode.addEventListener("click", () => {
el.value = code;
el.select();
document.execCommand("copy");
document.body.removeChild(div);
alert("Code Copied!\n\nYou can paste it into the developer tools of another browser e.g. firefox => chrome.");
})
div.appendChild(btnCode);
// "cancel" button
const btnCancel = document.createElement("button");
btnCancel.setAttribute("style", btnStyle);
btnCancel.innerText = "Cancel";
btnCancel.addEventListener("click", () => {
document.body.removeChild(div);
})
div.appendChild(btnCancel);
document.body.append(div);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment