Skip to content

Instantly share code, notes, and snippets.

@spapadim
Last active April 19, 2020 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spapadim/834771af56e5a5f64a24d65bd81f8723 to your computer and use it in GitHub Desktop.
Save spapadim/834771af56e5a5f64a24d65bd81f8723 to your computer and use it in GitHub Desktop.
Async function that fetches window variables into a Chrome content script (or another scope, in general).
// Based on https://stackoverflow.com/a/55431653/13321349
function fetchWindowVarsPromise(varNames, wnd = undefined) {
wnd = wnd || window;
return new Promise((resolve, reject) => {
// Generate random ID, to prevent other code from easily sending fake values
const randomId = uuid4();
// Register self-removing message handler first
const _messageHandler = (event) => {
console.log("DBG fetch vars:", event)
if (event.source != wnd) return;
const msg = event.data;
if (msg.randomId == randomId) {
event.preventDefault();
wnd.removeEventListener("message", _messageHandler);
resolve(msg.vars);
}
}
wnd.addEventListener("message", _messageHandler);
// Inject IIFE that sends message with variable values
const script = wnd.document.createElement("script");
script.type = "text/javascript";
script.id = 'varMessageSender';
script.textContent = `
(function (randomId, varNames) {
const msg = { randomId: randomId, vars: {} };
for (const varName of varNames) {
msg.vars[varName] = window[varName];
}
window.postMessage(msg, '${wnd.origin}');
})('${randomId}', ${JSON.stringify(varNames)});`;
wnd.document.body.append(script);
}); // end new Promise
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment