Search code examples
google-chrome-extensionmessagecontent-script

Can't send a message from background page to content script at Chrome Extension


I have this at my Background page:

function go(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});

}

go();

And this at my content script:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      alert(request.greeting);
  });

I expected the alert to launch as I enable the app, but nothing is happening. Am I missing something?

EDIT: The manifest.json:

{
  "manifest_version": 2,

  "name": "Naming",
  "description": "any",
  "version": "1.0",

  "permissions": [
    "tabs",
    "activeTab",
    "https://google.com.br/"
  ],

 "background": {"scripts":["background.js"]},

  "content_scripts": [
    {
      "js": ["CLAWS_Content_Script.js", "jquery.js"],
      "css": ["CLAWS_Content_Script_CSS.css"],
      "matches": ["<all_urls>"]

    }
  ],

  "web_accessible_resources": [
        "CLAWS_Sem_Imagens.html",
        "icone_XVermelho.png"
  ]


}

The content script gets loaded, because other funtions it provides works perfectly. There are no errors at the console.


Solution

  • The message is sent when the browser starts or the extension is enabled but at that moment there is no active content script to receive it. Similarly, when you reload the webpage, your background page isn't reloaded, so no message is sent, and consequently, nothing is received.

    If you really want the alert to launch as I enable the extension, then inject the content script manually via chrome.tabs.executeScript, in which case you don't need "content_scripts" section in manifest.json.