Thanks for the quick reply, i tried the below code. The problem is , code is not passing to userscript.js for execution.
method used to pass the code:
chrome.runtime.sendMessage
Error executing code: No response received
// background.js
chrome.runtime.onInstalled.addListener( () => {
chrome.contextMenus.create({
id: "modifyElement",
title: "Modify Element",
contexts: ["all"]
});
chrome.userScripts.configureWorld({
csp: "script-src 'self' 'unsafe-eval';",
messaging: true
})
chrome.userScripts.register([{
id: "modifyElementScript", // Add an ID for the user script
js: [{ file: "userScript.js" }],
matches: ["http://*/*", "https://*/*", "file://*/*"], // Specify valid URL schemes
runAt: "document_end",
world: "MAIN",
allFrames: true
}]).then(() => {
console.log("User script registered successfully.");
}).catch((error) => {
console.error("Error registering user script:", error);
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "modifyElement" && tab && tab.id) {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["contextMenu.js"]
}).then(() => {
console.log("contextMenu.js executed successfully.");
}).catch((error) => {
console.error("Error executing contextMenu.js:", error);
});
}
});
//contextmenu.js let some_code = "console.log('some message')"
chrome.runtime.sendMessage({ action: 'executeCode', some_code: codes }, (response) => {
if (response && response.success) {
console.log("Code executed successfully.");
} else {
console.error(response)
console.error("Error executing code:", response ? response.error : "No response received");
}
});
//userscript.js(() => {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log("userScript.js received message:", message);
if (message.action === 'executeCode') {
try {
eval(message.code);
sendResponse({ success: true });
} catch (error) {
console.error("Error executing code:", error);
sendResponse({ success: false, error: error.message });
}
}
})
})