zoukankan      html  css  js  c++  java
  • 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事件,则可以知道连接关闭。

      

      

  • 相关阅读:
    python if __name__ == '__main__' 作用
    Python pandas.DataFrame调整列顺序及修改index名
    Abp + gRpc 如何实现用户会话状态传递
    ASP .NET CORE 根据环境变量支持多个 appsettings.json
    [Abp 源码分析]九、事件总线
    [Abp 源码分析]八、缓存管理
    [Abp 源码分析]七、仓储与 Entity Framework Core
    基于阿里云 DNS API 实现的 DDNS 工具
    CentOS 7.4 安装 K8S v1.11.0 集群所遇到的问题
    [Abp 源码分析]六、工作单元的实现
  • 原文地址:https://www.cnblogs.com/nnavvi/p/5610785.html
Copyright © 2011-2022 走看看