谷歌插件消息传递

谷歌插件消息传递
1.简单消息传递
a.应用->脚本
chrome.runtime.sendMessage({greeting: "您好"}, function(response) {
 console.log(response.farewell);
});
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "来自内容脚本:" + sender.tab.url :
                "来自应用");
   if (request.greeting == "您好")
     sendResponse({farewell: "再见"});
}
);

b.脚本->应用

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
 chrome.tabs.sendMessage(tabs[0].id, {greeting: "您好"}, function(response) {
   console.log(response.farewell);
 });
});
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "来自内容脚本:" + sender.tab.url :
                "来自应用");
   if (request.greeting == "您好")
     sendResponse({farewell: "再见"});
}
);
//tabs[0].id为tab的id值
2.持久链接
a.应用->脚本
var port = chrome.runtime.connect({name: "敲门"});
port.postMessage({joke: "敲门"});
port.onMessage.addListener(function(msg) {
 if (msg.question == "是谁?")
    port.postMessage({answer: "女士"});
 else if (msg.question == "哪位女士?")
    port.postMessage({answer: "Bovary 女士"});
}
);
b.脚本->应用
runtime.connect替换为 tabs.connect
 
 
原文地址:https://www.cnblogs.com/luotingliang/p/7251434.html