Reputation: 259
i'm trying to send a message to my content script from the background, along with the menu ID that was clicked (which works perfectly now). After looking at similair questions i followed the guide from google developer on message passing here. but it doesnt seem to work for me as i get an uncaught event handler.
Manifest
"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"]
}
]
}
Background
// 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!");
}
});
});
});
Content
//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"});
});
Error Message
extensions::uncaught_exception_handler:8 Error in event handler for (unknown): TypeError: Cannot read property 'gotIt' of undefined
This is a follow up to a previous question i had about context menu's here. ive created a new question as a result of the answer there and code has changed enough that i think its best to ask a new here.
Upvotes: 0
Views: 233
Reputation: 10897
There is a typo in your content.js
,
request.menuID == "4"
should be
request.menuId == "4"
Besides, you could make your background.js
more robust by checking if response is undefined.
if (typeof response !== "undefined" && response.gotIt == "Got it") {
console.log("Got it!");
}
Upvotes: 2