Yes this can be done for MV3, here's what you need to do:
- Store the JS Snippet: First, you store your JavaScript code as a string in chrome.storage.local.
- Content Script: Write a content script that fetches the stored JS snippet from chrome.storage.local.
- Injecting the Script: Use the chrome.scripting.executeScript function to inject your content script into the web pages.
- Permissions: Make sure the correct permissions are declared in your manifest.json (like "storage", "scripting", and host permissions for the pages you want your script to run on).
Since you said you cannot find any examples, here is sample code for demonstration purposes for the implementation:
manifest.json
{
"manifest_version": 3,
"name": "Your Extension",
"version": "1.0",
"permissions": [
"storage",
"scripting",
"<all_urls>" // or specify specific sites
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"], // or specify specific sites
"js": ["contentScript.js"]
}
],
You'll need a background.js (or similar) which listens for changes in your storage.local event, for example:
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace === "local" && changes.yourSnippetKey) {
// Inject the content script when the stored code changes
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
files: ['contentScript.js']
});
});
}
});
Finally, a contentScript.js (or similar) that fetches the stored JS snippet for execution:
chrome.storage.local.get(['yourSnippetKey'], function(result) {
if (result.yourSnippetKey) {
const script = result.yourSnippetKey;
try {
// Execute the script
(new Function(script))();
} catch (error) {
console.error('Error executing the stored script:', error);
}
}
});
This uses
new Function(script) instead of
eval() to execute the string, it should work for your use case, just be wary of the dynamic execution of JS code here, handle it appropiately.
Thanks,
Deco