最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Making chrome extension and chrome.runtime.onMessage isn't receiving the message - Stack Overflow

programmeradmin1浏览0评论

Here is the code in my event page:

chrome.runtime.onInstalled.addListener(function (){
    chrome.contextMenus.create
        ({
            "title": "Test",
            "contexts": ["all"],
            "id": "menu"
        });
    chrome.contextMenus.create
        ({
            "title": "Dummy",
            "contexts": ["all"],
            "id": "dummy",
            "parentId": "menu"
        });
});

chrome.contextMenus.onClicked.addListener(onClickHandler);

function onClickHandler (info, tab) {
    if(info.menuItemId == "dummy"){
        chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
            console.log(response.farewell);
        });  
    }
}

And here is the code in my content script straight from the chrome message passing documentation:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

The onClickHandler in the event page is being triggered, but it seems like the sendMessage method isn't working. The onMessage listener isn't receiving any information, so it doesn't log anything to the console or even send a response. This causes the original sendMessage callback to throw an exception because response.farewell isn't even defined. Does anybody know why the code doesn't seem to work.

The error:

Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined

Here is the code in my event page:

chrome.runtime.onInstalled.addListener(function (){
    chrome.contextMenus.create
        ({
            "title": "Test",
            "contexts": ["all"],
            "id": "menu"
        });
    chrome.contextMenus.create
        ({
            "title": "Dummy",
            "contexts": ["all"],
            "id": "dummy",
            "parentId": "menu"
        });
});

chrome.contextMenus.onClicked.addListener(onClickHandler);

function onClickHandler (info, tab) {
    if(info.menuItemId == "dummy"){
        chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
            console.log(response.farewell);
        });  
    }
}

And here is the code in my content script straight from the chrome message passing documentation:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

The onClickHandler in the event page is being triggered, but it seems like the sendMessage method isn't working. The onMessage listener isn't receiving any information, so it doesn't log anything to the console or even send a response. This causes the original sendMessage callback to throw an exception because response.farewell isn't even defined. Does anybody know why the code doesn't seem to work.

The error:

Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined
Share Improve this question asked Feb 19, 2015 at 21:26 m0menim0meni 16.5k18 gold badges87 silver badges148 bronze badges 2
  • Probably duplicate with this one: stackoverflow./questions/26296181/… – Dayton Wang Commented Feb 19, 2015 at 22:10
  • 1 @gui47 Not a duplicate because I already used tabs.sendMessage instead of runtime.sendMessage which is the mistake they made. – m0meni Commented Feb 19, 2015 at 22:21
Add a ment  | 

3 Answers 3

Reset to default 4

For anybody else having problems, my issue was trying to send a message to a content script with the chrome.runtime API.

In order to send messages to a content script you have to use the chrome.tabs instead like this: chrome.tabs.sendMessage(tabId, message, options, response):

Sending a request from the extension to a content script looks very similar, except that you need to specify which tab to send it to.

Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back.

API docs: https://developer.chrome./extensions/tabs#method-sendMessage

Turns out there wasn't a problem with the code in the content script or the event page.

This thread: Chrome extension Content Script not loaded until page is refreshed

Helped me realize that the content script wasn't running because of the site I was testing it on, and because it wasn't running it obviously couldn't listen for any events.

I was facing an issue in which my working code of sending messages stopped working.

I realized that the issue was with the tabid. There were multiple windows of the browser opened and I was missing the activeWindow attribute to fetch the active tabs.

The following code snippet worked for me.

const fetchTabs = () => {
 return new Promise((resolve, reject) => {
  chrome.tabs.query({ active: true, currentWindow: true }, resolve);
 });
};

Notice the activeWindow attribute.

发布评论

评论列表(0)

  1. 暂无评论