简体   繁体   中英

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

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM