私は、コンテンツのスクリプトにバックグラウンドでメッセージを送信しようとしていますが、これはクリックされたメニューID(これは現在完全に動作しています)です。 similairの質問を見て、私はhereを渡すメッセージのgoogle開発者からのガイドに従った。それは私が捕まえられていないイベントハンドラを取得するように私のために働くように見えません。Chromeプラグイン - コンテンツへのメッセージの送信
マニフェスト
"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 Error in event handler for (unknown): TypeError: Cannot read property 'gotIt' of undefined
は、これは私は、コンテキストメニューのhereについて持っていた前の質問へのフォローアップです。 iveはそこでの答えの結果として新しい質問を作成し、コードは十分に変更されているので、ここで新しい質問をするのが最善だと思います。
正確なエラーメッセージを挿入できますか? – Xan
こんにちは@Xanあなたの助けを感謝iveは正確なエラーメッセージを追加し、それをちょうど入れて、それをメインポストに追加したスクリーンショットを撮った。 – Lmnoppy
これは、おそらくコンテンツスクリプトがアクティブなタブで聞くことができないことを意味します。どのように注入されますか?また、コールバックで 'chrome.runtime.lastError'をチェックしてください。 – Xan