Search code examples
javascriptgoogle-chrome-extensioncontent-scriptmessage-passing

Passing message from content script in Chrome extensions


I want to run a content script to identify the first image that links somewhere and return the link to the background script. But I can't pass any messages between them, and I don't know why. Much of the code is comment, I'm trying to simply test if the content script is executing by telling it to change the first header to "test" (since the only thing I can do without messages is change a page's HTML and CSS). The code follows: EDIT: full updated code

Background script:

chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.query({active:true, currentWindow:true}, function(tabs)
{
    chrome.tabs.executeScript(tabs[0].id, {file:"content.js"}, function ()
    {
        console.log("sending first time");
        console.log(tabs[0].id);
        chrome.tabs.sendMessage(tabs[0].id,{test: "test"}, function (response)
        {
            if (undefined == response)
            {
                console.log ("first one didn't work");
                chrome.tabs.sendMessage(tabs[0].id, {test: "test"}, function (response)
                {
                    console.log(response.test);
                });
            }
        });
    });
});
});

Content Script:

chrome.runtime.onMessage.addListener( function (msg, sender, sendResponse)
{
/*var test1 = document.getElementsByTagName("h1")[0];
test1.innerHTML="test";*/
sendReponse({test: "123"});
/*var parentList =document.getElementsByTagName("a");
var link = "";
var child;
for (var i=2; i<parentList.length;i++)
{
    child=parentList[i].firstChild;
    if ("IMG"==child.nodeName)
    {
        link=parentList[i].href;
        break;
    }
}
teste1.innerHTML=link;
var answer = new Object();
Answer.link = link;
teste1.innerHTML=answer.link;
sendResponse({messager:answer});*/
});

Solution

  • I was testing the extension at the extension page itself. But it seems you can't inject javascript in it (probably because it is a browser's settings page). It worked nicely on other pages.