Skip to content

Instantly share code, notes, and snippets.

@tokisakiyuu
Last active April 8, 2022 08:02
Show Gist options
  • Save tokisakiyuu/030f963f0666242eed348693d0ccc076 to your computer and use it in GitHub Desktop.
Save tokisakiyuu/030f963f0666242eed348693d0ccc076 to your computer and use it in GitHub Desktop.
Chrome Extension manifest v3 inject script to page
const nullthrows = (v) => {
if (v == null) throw new Error("it's a null");
return v;
}
function injectCode(src) {
const script = document.createElement('script');
// This is why it works!
script.src = src;
script.onload = function() {
console.log("script injected");
this.remove();
};
// This script runs before the <head> element is created,
// so we add the script to <html> instead.
nullthrows(document.head || document.documentElement).appendChild(script);
}
injectCode(chrome.runtime.getURL('/myscript.js'));
{
"name": "example",
"version": "1.0",
"description": "example extension",
"manifest_version": 3,
"content_scripts": [
{
"matches": ["https://*/*"],
"run_at": "document_start",
"js": ["inject.js"]
}
],
"web_accessible_resources": [
{
"resources": [ "myscript.js" ],
"matches": [ "https://*/*" ]
}
]
}
window.variableInMainContext = "hi"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment