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;}); 的形式。

原文地址:https://www.cnblogs.com/xiaoqisfzh/p/5567179.html