1

I am trying to get extension preferences in content script by asking from background.js.

contentscript.js

chrome.runtime.sendMessage({'action' : 'preferences'}, 
    function(prefs) {
        console.log(prefs);
    }
);

background.js

function onRequest(request, sender, callbackOfContentScript) {
    chrome.storage.sync.get(null, function(items){
        callbackOfContentScript(items);
    });
}
chrome.runtime.onMessage.addListener(onRequest);

console.log in content script returns undefined.

What is the issue here?

Makyen
  • 31,849
  • 12
  • 86
  • 121
Nico Neill
  • 113
  • 2
  • 8
  • 1
    What is `onRequest`? Do you use [`chrome.runtime.onMessage.addListener`](https://developer.chrome.com/apps/messaging#simple) ? – Denis L Sep 07 '17 at 09:53
  • yes exactly forget to add that. I am adding now. – Nico Neill Sep 07 '17 at 09:58
  • It would be easier to store your preferences in `storage.local`. `storage.local` is directly available to your content script, in addition to scripts in the background context. – Makyen Sep 08 '17 at 02:41

1 Answers1

2

You use an async message passing. The onMessage docs says that you have to return true in a sendResponse callback if you are going to make it async.

...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, the solution will be:

background.js

function onRequest(request, sender, callbackOfContentScript) {
    chrome.storage.sync.get(null, function(items){
        callbackOfContentScript(items);
    });
    return true; // <-- it makes the job
}
chrome.runtime.onMessage.addListener(onRequest);
Denis L
  • 3,209
  • 1
  • 25
  • 37