我无法在 current_script 和背景之间建立有效的交换消息。错误信息是:
Error in event handler for 'undefined': Cannot read property 'farewell' of undefined TypeError: Cannot read property 'farewell' of undefined
at chrome-extension://lanofchlikjdallgfmhbbijdglepcomm/script.js:29:23
at <error: illegal access>
at Event.dispatchToListener (event_bindings:356:21)
at Event.dispatch_ (event_bindings:342:27)
at Event.dispatch (event_bindings:362:17)
at Object.chromeHidden.Port.dispatchOnDisconnect (miscellaneous_bindings:258:27)
我使用 Google API Simple one-time requests并有以下星座:
mainfest.json
{
"manifest_version": 2,
"name": "Facebook Cage",
"description": "Facebook Cage hilft dir den Inhalt deiner Facebook Seite anzupassen.",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["popup.js"]
},
"content_scripts": [
{
"matches": ["https://www.facebook.com/*"],
"js": ["script.js"]
}
],
"permissions": [
"https://facebook.com/",
"storage",
"tabs"
]
}
脚本.js
document.onclick = function (){
if(document.URL=="https://www.facebook.com/"){
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
}
}
popup.js
chrome.storage.sync.get('url', function(result) {
!!result['url'] ? $("#input-area").val(result['url']) : "";
});
$("#save").click(function() {
chrome.storage.sync.set({'url': $("#input-area").val()});
window.close();
return(false);
});
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"});
});
或许你能帮忙,谢谢!
编辑:问题出在清单逻辑中。我有三个组件:popup.js 和 script.js。popup.js 嵌入在 popup.html 中。script.js 作为内容脚本。缺少的是背景逻辑,例如 backgorund.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")
sendResponse({farewell: "goodbye"});
});
在 background.js 中并将其链接到清单中
"background": {
"scripts": ["background.js"]
},
总而言之,我最终删除了 background.js 中的后台登录,从那里也可以使用存储吸气剂。