'Chrome Extension: How do I inject a script that the user provided?
I'm making an extension for chrome where the user can input a script, then press "run" to inject it into the current tab. I am using MV3 (manifest v3). Are there any ways to do this?
My code:
HTML:
<div class="scriptrunner">
<h1>Script Runner</h1>
<textarea placeholder="Enter script here" id="script"></textarea>
<button id="run">Run Script</button>
</div>
Javascript:
let button = document.getElementById("run");
button.addEventListener("click", async () => {
let input = document.getElementById("script");
let script = input.value;
// this is where the script would be ran
});
I've tried the following:
- Using
chrome.scripting.executeScript()
- Using
eval()
- Using
chrome.scripting.executeScript()
to insert a script tag with a function, then running the function
I just started working on chrome extensions, so maybe I missed something, or this is just impossible.
Solution 1:[1]
Executing arbitrary user code isn't yet implemented in ManifestV3.
Meanwhile we can create a script element in the page:
async function execInPage(code) {
const [tab] = await chrome.tabs.query({currentWindow: true, active: true});
chrome.scripting.executeScript({
target: {tabId: tab.id},
func: code => {
const el = document.createElement('script');
el.textContent = code;
document.documentElement.appendChild(el);
el.remove();
},
args: [code],
world: 'MAIN',
//injectImmediately: true, // Chrome 102+
});
}
execInPage('console.log(123)');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |