Saurabh Saxena
Saurabh Saxena

Reputation: 3205

Message Passing from Content Scripts to Background Page in Chrome Extensions

Google Chrome Extensions Message Passing Problem :

In this Chrome Extension

My Popup Page:

chrome.browserAction.onClicked.addListener(getMessage);
getMessage();

function getMessage()
{
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
            console.log(response.farewell);
        });//getting response from content script
    });
}

My Script Page :

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

I am not getting any response from the content script.

Edits:

As per @serg , i have moved the code to the background page. But still, it is not working

Upvotes: 0

Views: 871

Answers (1)

serg
serg

Reputation: 111265

You can't have chrome.browserAction.onClicked listener if you have popup page attached to the browser action button, it won't fire.

  • Remove popup, leave only button
  • Move everything into background page.
  • Replace tab.id with null.
  • Remove createFile(); call at the beginning as it won't do anything in this case (content script isn't ready to listen yet).
  • Don't use alerts for debugging extension, use console.log().

Upvotes: 4

Related Questions