Chrome扩展程序中PageAction,背景页面和ContentScript之间的通信

Dig*_*kam 0 google-chrome-extension

据我了解,无法直接在Page Action和Cotent Script之间进行通信,所以我这样做:

在page_action.html中:

chrome.extension.sendRequest(
    {to:"background",key:"color",val:"red"},
    function(response) {
        console.log(response) ;
    }
) ;
Run Code Online (Sandbox Code Playgroud)

在background.js中

chrome.extension.onRequest.addListener(
    function(request,sender,sendResponse) {
        if (request.to == "background") {
            console.log("Request recieved to Background") ;
            request.to = "content" ;
            chrome.extension.sendRequest(request,function(response) {
                sendResponse(response) ;
            }) ;
        }
    }
) ;
Run Code Online (Sandbox Code Playgroud)

在content.js中

(function(){
    // ...
    // Do something initial
    // ...
    // Now start to listen
    chrome.extension.onRequest.addListener(
        function(request,sender,sendResponse) {
            if (request.to == "content") {
                // Do something with request.key and request.val
                console.log("Request recieved to Content Script") ;
                sendResponse({status:'from content'}) ;
            }
        }
    ) ;
}()) ;
Run Code Online (Sandbox Code Playgroud)

Page Action和Background之间的通信工作正常,但是Background和Content Script之间没有任何反应。我在这里想念什么?如何正确沟通?最重要的是,还有另一种方法可以使通信从Page Action到Content Script更直接吗?

Bea*_*ist 5

幸运的是,有一种方法可以直接在a Page Action和a 之间进行通信Content Script,并且可以通过该tabs.sendMessage方法进行通信。

您可以id从chrome.pageAction.onClicked或从一个简单的获取chrome.tabs.query。

获得要向其发送消息的选项卡的ID后,就可以Page Action像这样从您的消息发送消息:

page_action.html

chrome.tabs.query({active:true,currentWindow:true},function(tabs){
  chrome.tabs.sendMessage(tabs[0].id,{message:"text"}, function(response){
    //If you need a response, do stuff with it here
  });
});
Run Code Online (Sandbox Code Playgroud)

content.js

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  //Do stuff here
  //sendResponse({message:"stuff"});
});
Run Code Online (Sandbox Code Playgroud)

顺便说一句,sendRequest并onRequest已被其Message同行取代。