Question

I know it's been here like thousand times, but I'm stuck now. I've read plenty of answers and studied the code.google.com but didn't succeed. I am trying to send a request in a chrome extension from background.html to contentscript.js. I managed to get it work the other way though.

Code inside background.html:

  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
      console.log(response.farewell);
     });
  });

Code inside contentscript.js:

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
    else
      sendResponse({farewell: "nope"});
});

The manifest.json should be fine as the communication is working backwards and anything else works properly. Thank you!

Was it helpful?

Solution

Your code is good, there must be something wrong with your trigger. I created a simple extension using your code and it worked. Add these two bits to your background and contentscript. Then rmb on any page and choose 'Send Message.' You should receive an alert.

Background.html

var menuid = chrome.contextMenus.create({"title":"Send Message", "onclick": SendMessage, "documentUrlPatterns":["http://*/*"]});

function SendMessage() {        
    chrome.tabs.getSelected(null, function(tab) {
            chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
                console.log(response.farewell);
             });
    });
}

contentscript

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello") {
            alert('hello');
      sendResponse({farewell: "goodbye"});
        }
    else
        {
            alert('goodbye');
      sendResponse({farewell: "nope"});
        }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top