I am creating a Google Chrome extension with MV3. The extension is basically a popup with a text input where the user can input their JavaScript code and a button to inject it into the current page.
So, my question is, how can I execute the JavaScript code from the user?
This is the code of my popup.js, which basically adds an event to the inject code button and executes the JavaScript code from the textarea of my popup.
const jsInput = document.querySelector("#js-input");
const injectBtn = document.querySelector("#inject-btn");
injectBtn.addEventListener("click", async () => {
const jsCode = jsInput.value;
const id = await getTabId();
chrome.scripting.executeScript({
target: {tabId: id},
args: [jsCode],
func: (jsArg) => {
//Here is where i dont know how to transform the js code string to a javascript funcion
}
});
})
async function getTabId() {
const queryOptions = { active: true, currentWindow: true };
const { id } = (await chrome.tabs.query(queryOptions))[0];
return id;
}
I've already tried using eval(jsCode), but I got this error:
Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules
I also tried to use a Function object, but encountered the same error. Additionally, I attempted to create a script element, but encountered the same issue.