3

I am trying to set up my content_script.js to sendMessage to background.js. Background.js is able to receive the message and act on it, but content_script.js is having trouble receiving/printing it out.

content_script.js

chrome.runtime.sendMessage({method: "getSettings"}, function(response) {
    console.log(response.data);
    console.log("This is not printing either");
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSettings") {
        chrome.storage.sync.get(null, function (val) {
            sendResponse({data: "test"});
            console.log("Responding: " + val.radioSettings);
        });
    }
});

Console.log in background.js prints the correct message from chrome.storage, but the console.log in my content_script.js is never printing.

I feel like this is close, but just missing something small. Here is part of my manifest:

manifest.json

{
  "version": "0.0.1",
  "manifest_version": 2,
  "browser_action": {
    "default_icon": "icons/icon19.png",
    "default_popup": "popup.html"
  },
  "background": {
    "scripts": ["js/background.js"]
  },
  "permissions": [
    "storage",
    "tabs"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["js/jquery-1.11.3.min.js", "js/content_script.js"]
    }
  ]
}
Kevin
  • 753
  • 2
  • 8
  • 18

1 Answers1

1

That solved it -- thanks for duplicate question link.

To make it easier for others, here is what the other answer said:

From the documentation for chrome.runtime.onMessage.addListener:

This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

So you just need to add return true; after the [end of addListener] to indicate that you'll call the response function asynchronously.

Here is the correct version of the code:

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSettings") {
        chrome.storage.sync.get(null, function (val) {
            sendResponse({data: "test"});
            console.log("Responding: " + val.radioSettings);
        });
    }
    return true;
});
Community
  • 1
  • 1
Kevin
  • 753
  • 2
  • 8
  • 18