Bolboa Bolboa - 24 days ago 11
Javascript Question

send message to active tab

I am using

executeScript
to run in the current active tab. But inside its callback function I want to send a message to the script being executed...

chrome.tabs.executeScript(null, {
file: 'src/js/scripts/extractCSS.js'
}, function() {
chrome.tabs.sendMessage(this.props.source);


this.props.source
is an object I am trying to pass. And inside
src/js/scripts/extractCSS.js
I am trying to catch the message...

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
console.log(message);
});


However I get the following error...

Error in response to tabs.executeScript: Error: Invocation
of form tabs.sendMessage(object) doesn't match definition
tabs.sendMessage(integer tabId, any message, optional object
options, optional function responseCallback)


From what I gather, I need to define
tabId
, but I just need to send the message to the active tab. I tried adding
null
for
tabId
but it still gives me an error.

How can I fix this?

Answer

Even though its a active tab, you will have to pass the tabId. chrome.tabs.query can be used to get the tabs. You can do it the following way:

chrome.tabs.query(
    { currentWindow: true, active: true },
    function (tabArray) {
        chrome.tabs.executeScript(tabArray[0].id, {
            file: 'src/js/scripts/extractCSS.js'
         }, function() {
            chrome.tabs.sendMessage(this.props.source);

        })
    }
);

As there can be only one active tab in current window, tabArray will have one element only and then id attribute can be accessed.