Skip to content

Instantly share code, notes, and snippets.

@domtronn
Created June 3, 2021 07:33
Show Gist options
  • Save domtronn/76eb28cba242e0005302effb86c6cd1f to your computer and use it in GitHub Desktop.
Save domtronn/76eb28cba242e0005302effb86c6cd1f to your computer and use it in GitHub Desktop.
Background chrome script to download cookies for a domain
const DOMAIN = 'calendar.google.com'
const FILENAME = 'gcal-cookies.txt'
/** --------
This background chrome extension script will download all cookies
for a page into a file periodically when you visit, useful for if
you can't generate your own API Access tokens or service accounts
but want to use your logged in cookies to read from a service,
e.g. google calendar
Manifest
{
"name": "Cookie Exporter",
"version": "1.0",
"manifest_version": 2,
"permissions":[
"tabs",
"downloads",
"cookies",
"*://*.google.com/*"
],
"background": {
"scripts": ["background.js"]
}
}
*/
let lastDownload = 0
chrome.tabs.onHighlighted.addListener(async _ => {
let queryOptions = { active: true, currentWindow: true }
chrome.tabs.query(queryOptions, ([tab]) => {
if (tab.url.includes(DOMAIN)) {
// Check to see if we've downloaded cookies recently
const timeDiffHours = (new Date() - lastDownload) / 1000 / 60 / 60
if (timeDiffHours < 12) {
console.log(`Skipping download: ${Math.floor(timeDiffHours)}hrs since last download`)
return
}
chrome.cookies.getAllCookieStores(stores => {
let { id: storeId } = stores.find(s => s.tabIds.includes(tab.id)) || {}
if (!storeId) return
chrome.cookies.getAll({ storeId, url: tab.url }, (cookies) => {
const cookieString = cookies
.reduce((acc, it) => acc + `${it.name}=${it.value}; `, '')
const cookieDataUri = encodeURI(`data:text/plain,${cookieString}`)
chrome.downloads.download({
url: cookieDataUri,
filename: FILENAME,
conflictAction: 'overwrite'
}, () => {
console.log(`Downloading cookies`)
lastDownload = new Date()
})
})
})
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment