最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - send message to active tab - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Nov 16, 2016 at 19:57 buydadipbuydadip 9,45722 gold badges93 silver badges160 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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.

发布评论

评论列表(0)

  1. 暂无评论