我需要有两种类型的通信,单一消息传递用于检索初始信息和长期消息传递。消息传递与外部网页通信如下。 网页中返回的响应总是未定义的! 问题在哪里?
的manifest.json
{
"manifest_version": 2,
"name": "external-long-lived",
"description": "message test",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"],
"persistent": true
},
"permissions": [
"tabs",
"http://*/*",
"management"
],
"offline_enabled": true,
"externally_connectable": {
"matches": ["http://localhost:8081/myWeb.html"],
"accept_tls_channel_id":true
}
}
background.js
//single messaging part
chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse){
if(navigator.appVersion.indexOf("Win"!=-1)) {myOS = "Windows";}
if(navigator.appVersion.indexOf("Mac"!=-1)) {myOS = "MacOS";}
if(navigator.appVersion.indexOf("X11"!=-1)) {myOS = "UNIX";}
if(navigator.appVersion.indexOf("Linux"!=-1)) {myOS = "Linux";}
chrome.management.get("iacgjcchbmaofapfmlfmdneaaimagjej",function(result){
if(result) myVersion = "1.0";
});
if(request.message == "initialize" && myOS = "Windows" && myVersion == "1.0"){
sendResponse({version:"1.0" , OS:"Windows"});
}
return true;
};
//long-lived messsaging part
console.log("hey back");
chrome.runtime.onConnectExternal.addListener(function(port){
port.onMessage.addListener(function(message, sender){
if(message.greeting == "hello"){
console.log("message from content: " + message.greeting);
port.postMessage({greeting:"hey"});
}
else if(message.greeting == "salam"){
console.log("message from content: " + message.greeting);
port.postMessage({greeting:"H R U?"});
}
else if(message.greeting == "khobam")
{
console.log("message from content: " + message.greeting);
port.postMessage({greeting:"it's great"});
}
else{
console.log("background did not receive salam");
}
});
});
在myWeb.html(外部网页)中调用的content.js
//single messaging part
var extensionId = 'iacgjcchbmaofapfmlfmdneaaimagjej';
chrome.runtime.sendMessage(extensionId, {message:"initialize"},function(response){
console.log(response);
if(!response){alert("not installed");}
else{
console.log(response.version);
console.log(response.OS);
}
});
//long-lived messaging part
console.log("hey content");
var port = chrome.runtime.connect("iacgjcchbmaofapfmlfmdneaaimagjej",{name:"external-long-lived"});
port.postMessage({greeting:"hello"});
port.onMessage.addListener(function(message, sender){
if(message.greeting == "hey"){
console.log("message from background: " + message.greeting);
port.postMessage({greeting:"salam"});
}
else if(message.greeting == "H R U?"){
console.log("message from background: " + message.greeting);
port.postMessage({greeting:"khobam"});
}
else if(message.greeting == "it's great"){
console.log("message from background: " + message.greeting);
}
else{
console.log("content did not receive hello");
port.postMessage({greeting:"no salam"});
}
});
提前致谢