发送消息到活动选项卡

Bol*_*boa 3 javascript google-chrome-extension

我用来executeScript在当前活动选项卡中运行。但在其回调函数内,我想向正在执行的脚本发送一条消息......

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

this.props.source是我试图传递的一个对象。我在内心src/js/scripts/extractCSS.js试图捕捉到这个信息......

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
     console.log(message);
});
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误...

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)
Run Code Online (Sandbox Code Playgroud)

根据我收集的信息,我需要定义tabId,但我只需要将消息发送到活动选项卡。我尝试添加nullfortabId但它仍然给我一个错误。

我怎样才能解决这个问题?

fal*_*der 6

即使它是一个活动选项卡,您也必须通过tabId. chrome.tabs.query可用于获取选项卡。您可以通过以下方式进行操作:

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);

        })
    }
);
Run Code Online (Sandbox Code Playgroud)

由于当前窗口中只能有一个活动选项卡,tabArray因此只有一个元素,然后id可以访问属性。