Last active
April 8, 2022 08:02
-
-
Save tokisakiyuu/030f963f0666242eed348693d0ccc076 to your computer and use it in GitHub Desktop.
Chrome Extension manifest v3 inject script to page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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://*/*" ] | |
} | |
] | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.variableInMainContext = "hi" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment