I'm working on a Chrome extension that involves message passing from the background script to the content script via a message port. According to the documentation I have to first query for the tab where the content script I want to connect to is running and then open a port using that Tab's ID. So my background script and content script look like the following:
background.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var port = chrome.tabs.connect(tabs[0].id, { name: "example" });
port.postMessage("hello world");
});
content_script.js
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
console.log(msg);
});
});
And no message is printed to the console. I did some debugging first by putting break point on this line in content_script port.onMessage.addListener(function(msg) {
which was never hit. This led me to believe that the port was never opened in background.js. So next, I put a break point in background.js at this line var port = chrome.tabs.connect(tabs[0].id, { name: "example" });
by using the dev tools accessed here
and it turns out that my query isn't actually returning any tabs into the callback so tabs[0].id
raises an error. I'm guessing that once I get this tab query to work the message passing will start working, so does anyone have any idea what's going on here that I can't query for the current, active tab? I've seen this exact query used in many other StackOverflow responses and it's in an example in the message passing docs.