I am currently facing an issue with injecting a content script file into a newly created tab. The problem lies in the fact that I keep receiving an error stating
chrome.tabs.executeScript(...) is undefined
in the console output of the Popup. It may be worth mentioning that Vue is being used in this project. Let me provide you with some code snippets.
Let's start with the manifest:
{
"manifest_version": 2,
"name": "Example",
"description": "Performs common searches based on input",
"default_locale": "en",
"permissions": [
"<all_urls>",
"tabs"
],
"background": {
"scripts": [
"js/background.js"
]
},
"browser_action": {
"default_popup": "popup.html",
"default_title": "Example",
}
}
Moving on to the code within the popup Vue component's "method" attribute:
search: function() {
const urls = Object.values(this.$store.state.urls);
urls.forEach((item, index) => {
chrome.tabs.create({ url: item }, (tab) => {
// Works!
chrome.tabs.executeScript(tab.id, { code: "console.log('Injected JS')" });
// Doesn't work..
chrome.tabs.executeScript(tab.id, { file: "/content-script.js" });
// Doesn't work..
chrome.runtime.sendMessage({ message: "Popup", tabId: tab.id })
});
});
}
The content script looks like this:
(function() {
console.log("Injected JS from file!");
})();
Lastly, background.js:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if(request.message === "Popup") {
console.log("Got message from popupJS in background.");
console.log("Tab id: " + request.tabId);
chrome.tabs.executeScript(request.tabId, { file: "/content-script.js" });
}
});
In the main code section, three different approaches were attempted:
- executeScript using the code option - successful.
- executeScript using the file option - unsuccessful.
- executeScript in the background script - also unsuccessful. This was expected to resolve the
error but unfortunately did not succeed even after printing the tab id.chrome.tabs.executeScript(...) is undefined
Considering a possible pathing issue with content-script.js, I referred to both the Chrome docs and the more informative Mozilla docs:
To ensure cross-browser compatibility, you can specify the path as a relative URL starting at the extension's root, for example: "/path/to/script.js".
The content script is located at extension-project/content-script.js in the project root. Although attempts were made by incorporating the project folder in the path string to cover all bases, no progress has been achieved.
If you have any insights or suggestions on where I might be going wrong, they would be greatly appreciated.