Digerkam
Digerkam

Reputation: 1921

Communication Between PageAction, Background Page And ContentScript In A Chrome Extension

As I understood there is no way to communication directly between Page Action and Cotent Script, so I do that:

In page_action.html:

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

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

In 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'}) ;
            }
        }
    ) ;
}()) ;

Communication between Page Action and Background works perfectly, but nothing happen between Background and Content Script. What am I missing here? How to communicate each other properly? And most of all, is there another way that let communication more directly from Page Action to Content Script?

Upvotes: 0

Views: 1859

Answers (1)

BeardFist
BeardFist

Reputation: 8201

Luckily, there is a way to communicate directly between a Page Action and a Content Script and that would be though the tabs.sendMessage method.

You can obtain the id either from chrome.pageAction.onClicked or from a simple chrome.tabs.query.

Once you have the ID of the tab you want to send a message to, just send the message from your Page Action like this:

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

content.js

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

On a side note, sendRequest and onRequest have been replaced with their Message counterparts.

Upvotes: 5

Related Questions