长效消息(long-lived connections)是现在消息的收发双方建立通道,然后通过这个通道收发消息。
连接主动方:
var port = chrome.runtime.connect({name: "con1"}); port.postMessage({cmd: "mycmd"}); port.onMessage.addListener(function(msg) {
if (msg.recmd== remycmd")
port.postMessage({cmd: "mycmd2"});
else if (msg.recmd== "remycmd2")
port.postMessage({cmd: "mycmd3"});
});
连接被动方:
chrome.runtime.onConnect.addListener(function(port) { console.assert(port.name == "con1"); port.onMessage.addListener(function(msg) {
if (msg.cmd== "mycmd")
port.postMessage({recmd: "remycmd"});
else if (msg.cmd == "mycmd2")
port.postMessage({recmd: "remycmd2"});
else if (msg.cmd== "mycmd3")
port.postMessage({recmd: "remycmd3"});
});
});