Chrome插件 - 向内容发送消息

时间:2016-05-16 15:04:08

标签: javascript google-chrome-extension

我正在尝试从后台向我的内容脚本发送一条消息,以及单击的菜单ID(现在可以正常工作)。在查看similair问题后,我按照谷歌开发人员的指南传递了消息here。但它似乎不适合我,因为我得到一个未被捕获的事件处理程序。

清单

"permissions": [
    "contextMenus",
    "background",
    "tabs",
    "activeTab",
    "storage",
    "https://ajax.googleapis.com/"
 ],

"background": {
    "persistent": false,
    "scripts": ["scrippy.js"] 
},

 "content_scripts": [
{
    "run_at": "document_end",
    "matches": ["http://*/*", "https://*/*"],
    "js": ["content.js"]
}
]
}

背景

// Create context menu type variable so that its easily changed for all of them
var type = ["editable"];

// Create context menu
// Parent item
var scrippyMenu = chrome.contextMenus.create({"id": "1", "title": "Scrippy", "contexts": type});

// Child 1
var menuChild1 = chrome.contextMenus.create({"id": "2", "title": "child1", "parentId": scrippyMenu, "contexts": type});

// Child 2
var menuChild2 = chrome.contextMenus.create(
{"id": "3", "title": "child2", "parentId": scrippyMenu, "contexts": type});

// sub child 1 of child 2
var menuChild3 = chrome.contextMenus.create(
{"id": "4", "title": "sub child", "parentId": menuChild2, "contexts": type});

// Create an on click event listener and send message to content.js
chrome.contextMenus.onClicked.addListener(function(info, tab) {

//check menu item being sent
console.log("Menu item ID: " + info.menuItemId + " was clicked");

//Send message to content.js with the current tab id and menuItemId clicked
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
     chrome.tabs.sendMessage(tabs[0].id, {menuId: info.menuItemId},

//On response from content.js log it to console.
function(response) {
if(response.gotIt == "Got it"){
            console.log("Got it!");
}
     });
   });
});

内容

//Listener waiting for messages
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

console.log(sender.tab ?
            "from a content script:" + sender.menuId : "from the extension");

//if message states menu id of 4 then send response back to background
if (request.menuID == "4") 

sendResponse({gotIt: "Got it"});

});

错误消息

  

extensions :: uncaught_exception_handler:8(未知)事件处理程序出错:TypeError:无法读取未定义属性'gotIt'

Error message screen grab

这是我之前关于上下文菜单here的问题的后续跟进。由于答案的结果,我已经创建了一个新问题,代码已经发生了很大变化,我认为最好在这里问一个新问题。

1 个答案:

答案 0 :(得分:2)

helloWorld()

中有拼写错误
content.js

应该是

request.menuID == "4"

此外,您可以通过检查响应是否未定义来使request.menuId == "4" 更加健壮。

background.js