chrome 插件开发 通讯机制

短链接(Simple one-time requests)

  发送消息:popup to background;background to popup;background to panel....除了( to content)

       

chrome.runtime.sendMessage(
    {greeting: "hello"}, function(response) {
          alert(response.farewell);                   
    }
)

  发送消息:*** to content

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        chrome.tabs.sendMessage(tabs[0].id, {greeting:'hello'}, function(response) {
                    console.debug(response.farewell)    
           });  
       })

  

  接受消息:所有

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"});
});

  

长链接(Long-lived connections)

  建立链接:除了(*** to content)之外

var port = chrome.runtime.connect({name: "topanel"});
    //建立链接
port.postMessage({greeting: "hello"});
    //发送消息
port.onMessage.addListener(function(msg) {
      //接收消息    
    if (msg.farewell== "goodbye")
        port.postMessage({answer: "goodbye"});
    else if (msg.question == "hello")
        port.postMessage({answer: "nice to meet u"});
});

  建立链接:*** to content

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
       var port = chrome.tabs.connect(tabs[0].id,{name:'topanel'}); //建立链接 
       port.postMessage({greeting: "hello"});   //发送消息
       port.onMessage.addListener(function(msg) {
        if (msg.farewell== "goodbye")
        port.postMessage({answer: "goodbye"});
    else if (msg.question == "hello")
        port.postMessage({answer: "nice to meet u"});
        }     
   }
)    

  监听链接:所有

chrome.runtime.onConnect.addListener(function(port) {
    console.assert(port.name == "topanel");
    port.onMessage.addListener(function(msg) {
        if (msg.greeting== "hello")
            port.postMessage({farewell: "hello"});
        else if (msg.answer == "nice to meet u")
            port.postMessage({farewell: "goodbye"});
    });
});

  

  关闭链接:

  链接的任何一方主动关闭链接时使用:port.disconnect()则关闭连接, 另一方监听 chrome.runtime.Port.onDisconnect事件,则可以知道连接关闭。

  

  

原文地址:https://www.cnblogs.com/nnavvi/p/5610785.html