我正在学习Chrome扩展程序不同部分之间传递的消息。如https://developer.chrome.com/apps/messaging中所述,我做了简单的扩展。但是它总是会报错:
Error handling response: TypeError: Cannot read property 'farewell' of undefined
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
我不知道为什么。我只是从chrome网站复制代码。我确实需要帮助解决此问题。 这是我的文件: manifest.json:
{
"manifest_version": 2,
"name": "Connect",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": [ "<all_urls>" ],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test"
},
"permissions": [
"activeTab",
"<all_urls>"
]
}
background.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")
sendResponse({farewell: "goodbye"});
});
如果我做错了什么,请指出。谢谢。