• chrome 插件


    扩展与浏览器间的通信,可以有两种形式:

        1)短连接   

            发送消息:chrome.runtime.sendMessage

            接收事件:chrome.runtime.onMessage.addListener

        2)长连接

             发送消息:var port = chrome.runtime.connect           

                           port.postMessage

            接收事件:port.onMessage.addListener

    Native Message机制的通信方式,也有两种形式:

        1)短连接

            发送消息:chrome.runtime.sendNativeMessage

        2)常连接

            发送消息:var port = chrome.runtime.connectNative

                          port.postMessage

            接收事件:port.onMessage.addListener

                          port.onDisconnect.addListener

    --------------------------------------------这里是分割线----------------------------------------------------------
    当插件的图标是否显示出来是取决于单个的页面时,应当选择page action;
    当其它情况时可以选择browser action。
    
    
    //connect to native host and get the communicatetion port  
    function connectToNativeHost(msg)  
    {  
        var nativeHostName = "com.my_company.my_application";  
        console.log(nativeHostName);  
        port = chrome.runtime.connectNative(nativeHostName);  
        port.onMessage.addListener(onNativeMessage);  
        port.onDisconnect.addListener(onDisconnected);  
        port.postMessage({message: msg});     
     }
     
     function onDisconnected()  
    {  
        console.log(chrome.runtime.lastError);  
        console.log('disconnected from native app.');  
        port = null;  
    }  
      
    function onNativeMessage(message) {  
        console.log('recieved message from native app: ' + JSON.stringify(message));  
    } 
    --------------------------------------------这里是分割线----------------------------------------------------------

    6、插件通信:

      6.1 background.js 和 content_script.js 通信推荐使用 chrome.extension.sendRequest()、chrome.extension.onRequest.addListener(function(request, sender, sendRequest){}); 的形式。

      6.2 其他页面调用 background.js 里的函数和变量时推荐在其他页面使用 var backgroundObj = chrome.extension.getBackgroundPage(); if(backgroundObj){ backgroundObj.func(param); }的形式。

      6.3 如果插件运行中会有多个tab页同时打开和加载,则需要注意通信过程中使用 tab.id 参数,因为每个加载插件的tab页都会保留自己的一个 content_script.js 运行,所以和 content_script.js 通信时需要指定是向哪个tab页进行通信;获取当前打开的 tab 页的 id 可以使用 chrome.tabs.getSelected(function(tab){current_tab_id = tab.id;}); 的形式。

  • 相关阅读:
    Windows 2008 R2 安装 Windows phone 7 开发环境
    win 7,win2008 无法给新建用户完全权限
    基于Ajax的Asp.Net 简易在线聊天室
    phpwind ecshop 用户整合
    UVALive 3942 Remember the Word(字典树+DP)
    UVA 11732 strcmp() Anyone? (压缩版字典树)
    UVA 11992 Fast Matrix Operations(线段树:区间修改)
    hdu 2222 Keywords Search(AC自动机模版题)
    动态规划基础练习笔记
    递归与分治策略基础练习笔记
  • 原文地址:https://www.cnblogs.com/xiaoqisfzh/p/5567179.html
Copyright © 2020-2023  润新知