• 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事件,则可以知道连接关闭。

      

      

  • 相关阅读:
    Linux安装MySQL5.7.25
    Linux配置jdk
    SpringBoot junit 测试
    SpringBoot jasypt 对配置文件项加密
    关于Hibernate级联操作的总结
    GROUP BY 和 ORDER BY一起使用时,要注意的问题!
    web.xml 中的listener、 filter、servlet 加载顺序及其详解
    Hibernate对象的生命周期(补充)
    hibernate--持久对象的生命周期介绍
    开发属于你自己的标签库!
  • 原文地址:https://www.cnblogs.com/nnavvi/p/5610785.html
Copyright © 2020-2023  润新知