清单
{
"manifest_version": 2,
"name": "sth",
"description": "sth",
"version": "0.1",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png"
},
"externally_connectable": {
"ids": [
"mmaocogodokhpkellandkpdknpnihple"
],
"matches": [
"https://*.google.de/*"
],
"accepts_tls_channel_id": false
},
"permissions": [
"activeTab"
]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "content.js"});
});
chrome.runtime.onMessageExternal.addListener( function(request, sender, sendResponse) {
console.log(request);
return true;
});
content.js
console.log("content");
var msg = { text: "test" };
chrome.runtime.sendMessage("mmaocogodokhpkellandkpdknpnihple", msg, function() {
console.log("content callback");
});
当我在https://www.googel.de时,点击该图标,然后查看"内容"和#34;内容回调"在控制台中,但请求未记录在后台脚本的控制台中。我可能在这里想念一些东西......?
(Linux上的Chrome 44)
答案 0 :(得分:1)
您自己的扩展程序内的邮件不是外部的。您需要使用onMessage
的常规无聊消息,而无需指定ID。
// background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "content.js"});
});
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
console.log(request);
return true; // Why? This keeps the communication channel open waiting,
// and then you won't see "content callback"
});
// content.js
console.log("content");
var msg = { text: "test" };
chrome.runtime.sendMessage(msg, function() {
console.log("content callback");
});
的确,也许回归true
让你感到困惑?当你打算异步调用sendResponse
时需要它,因此sendMessage
的回调在你执行之前不会触发。