从background.js发送消息到content.js会出错

时间:2016-08-23 16:39:30

标签: javascript google-chrome google-chrome-extension

我正在尝试从我的后台背景页面(sample.js)向content.js发送消息,我在控制台中收到以下错误:

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

我从chrome扩展页面上的消息传递文档中获取了以下代码。

的manifest.json

{
    "manifest_version": 2,
    "name": "Linky1",
    "description": "Save URL plugin",
    "version": "1.0",
    "background": 
     {
      "scripts": ["sample.js"], "persistent": false
     }, 
  "permissions": ["contextMenus","<all_urls>","storage","activeTab","tabs"],
   "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["content.js"],
        "run_at": "document_end"
      }
    ]

}

sample.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) 
{
    chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);});
});

content.js

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")
console.log("Working")
});

0 个答案:

没有答案