Skip to content

Instantly share code, notes, and snippets.

@Macil
Created March 7, 2018 00:49
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 Macil/fa9c1f150369dcd3e3a2550922771081 to your computer and use it in GitHub Desktop.
Save Macil/fa9c1f150369dcd3e3a2550922771081 to your computer and use it in GitHub Desktop.
This function allows you to load javascript from a remote url with an extension content script, and have the loaded javascript execute within the content script's isolated world.
async function loadInContentScript(url) {
// Note that this extension must either have permission to the domain of this
// URL, or the URL must be served with the correct CORS HTTP headers to allow
// this script to fetch it (ie. "Access-Control-Allow-Origin: *").
const response = await fetch(url);
const scriptText = await response.text();
// Let Chrome devtools know where this code came from.
const codeToRun = scriptText + "\n//# sourceURL=" + url + "\n";
// Put eval into a variable first and then call it so we get "indirect eval"
// behavior. A direct eval call is actually syntactically-special and has
// effects that we don't want. Code passed to a direct eval call has access
// to all of the local variables of the call site, and this prevents the
// javascript engine from many optimizations.
const indirectEval = eval;
indirectEval(codeToRun);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment