I have spent all day trying to figure this out and I seem to be getting nowhere, can someone share with me where I am going wrong?
I am trying to figure out how to correctly send a message, from a "background" script to a content script. I want to use onBeforeRequest()
as the trigger event, so that when it happens a message is to sent to the content script to get some information from the pages DOM.
The DOM part is not present in this example, I am struggling to just establish a working messaging pattern.
manifest file:
{
"name": "shell",
"manifest_version": 2,
"version": "1.0",
"background": {"scripts": ["background.js"]},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"permissions": ["tabs","activeTab", "webRequest", "<all_urls>"]
}
background.js file:
activeTab = browser.tabs.query({currentWindow: true,active: true,})
function sendMessageToTabs(activeTab) {
for (const tab of activeTab) {
browser.tabs.sendMessage(activeTab.id, { greeting: "Hi from background script" })
.then((response) => {
console.log("Message from the content script:");
console.log(response.response);
})
.catch(onError);
}
}
browser.webRequest.onBeforeRequest.addListener(sendMessageToTabs, {urls:["https://en.wikipedia.org/wiki/Vehicle"]});
Content.js file:
"use strict";
browser.runtime.onMessage.addListener((request) => {
console.log("Message from the background script:");
console.log(request.greeting);
return Promise.resolve({ response: "Hi from content script" });
});
How to trigger the event
Once I load the extension, I can trigger the on onBeforeRequest()
by visiting the Car page of Wikipedia and clicking on the Vehicle part, right under the article profile picture, as shown HERE.
The problem I am having
Is that when the event triggers I get an error in the DevTools console:
TypeError: activeTab is not iterable
I tried a number of ways to solve this issue but it just persists. Any help or pointers would be amazing. Cheers.