Chrome浏览器扩展开发系列之十三:消息传递Message
2015-09-30 10:41
483 查看
由于contentscripts运行在Web页面的上下文中,属于Web页面的组成部分,而不是GoogleChrome扩展程序。但是contentscripts又往往需要与GoogleChrome扩展程序的其他部分通信以共享数据。
这可以通过消息传递实现,通过彼此互相的消息的监听与反馈进行通信。一个消息可以包含任何有效的JSON对象,如null,boolean,number,string,array,object。
1)一次性请求与响应模式
对于一次性请求与响应模式,chrome.runtime.sendMessage(obj,function(response){})是从contentscripts发生请求消息给GoogleChrome扩展程序页面。
从GoogleChrome扩展程序页面发送请求消息给contentscripts的时候,需要给出当前tab的ID。
监听消息时,需要注册要监听的消息。
注意:如果为同一个消息注册了多个监听器,则只有第一个监听器能够调用sendResponse()方法,其他的监听器将被忽略。
2)保持长期连接的模式
对于保持长期连接的模式,在contentscripts与Chrome扩展程序页面之间建立通道(可以为通道命名),可以处理多个消息。在通道的两端分别拥有一个chrome.runtime.Port对象,用以收发消息。
在contentscripts主动建立通道如下:
在GoogleChrome扩展程序页面主动建立通道如下:
在contentscripts或GoogleChrome扩展程序页面,监听建立连接的请求如下:
在contentscripts或GoogleChrome扩展程序页面的任一端,调用chrome.runtime.Port.disconnect()则关闭连接,同时出发disconnect事件。这时,只有另一端监听chrome.runtime.Port.onDisconnect事件,则可以知道连接关闭。
3)GoogleChrome扩展程序之间消息模式
还可以在不同的GoogleChrome扩展程序之间发送消息,只要知道GoogleChrome扩展程序的ID。这使得GoogleChrome扩展程序可以发布服务为其他扩展程序所用。
这种GoogleChrome扩展程序之间的消息也分为一次性请求与响应模式和保持长期连接的模式。
GoogleChrome扩展程序监听调用其服务的消息如下:
发送调用服务的消息如下:
4)GoogleChrome扩展程序接收指定的Web页面发送的消息
GoogleChrome扩展程序可以与一些指定地点Web页面直接收发消息。
首先,在GoogleChrome扩展程序的manifest.json文件设置可以通信的Web页面范围:
其次,在GoogleChrome扩展程序中监听Web页面的消息如下:
最后,在指定的Web页面中,发送消息如下:
这可以通过消息传递实现,通过彼此互相的消息的监听与反馈进行通信。一个消息可以包含任何有效的JSON对象,如null,boolean,number,string,array,object。
1)一次性请求与响应模式
对于一次性请求与响应模式,chrome.runtime.sendMessage(obj,function(response){})是从contentscripts发生请求消息给GoogleChrome扩展程序页面。
从GoogleChrome扩展程序页面发送请求消息给contentscripts的时候,需要给出当前tab的ID。
chrome.tabs.query( {active:true,currentWindow:true}, function(tabs){ chrome.tabs.sendMessage( tabs[0].id, {greeting:"hello"}, function(response){ console.log(response.farewell); }); });
监听消息时,需要注册要监听的消息。
chrome.runtime.onMessage.addListener( function(request,sender,sendResponse){ console.log(sender.tab? "fromacontentscript:"+sender.tab.url: "fromtheextension"); if(request.greeting=="hello")//判断是否为要处理的消息 sendResponse({farewell:"goodbye"}); });
注意:如果为同一个消息注册了多个监听器,则只有第一个监听器能够调用sendResponse()方法,其他的监听器将被忽略。
2)保持长期连接的模式
对于保持长期连接的模式,在contentscripts与Chrome扩展程序页面之间建立通道(可以为通道命名),可以处理多个消息。在通道的两端分别拥有一个chrome.runtime.Port对象,用以收发消息。
在contentscripts主动建立通道如下:
varport=chrome.runtime.connect({name:"yisheng"});//通道名称 port.postMessage({joke:"Knockknock"});//发送消息 port.onMessage.addListener(function(msg){//监听消息 if(msg.question=="Who'sthere?") port.postMessage({answer:"yisheng"}); elseif(msg.question=="Madamewho?") port.postMessage({answer:"Madame...Bovary"}); });
在GoogleChrome扩展程序页面主动建立通道如下:
chrome.tabs.query( {active:true,currentWindow:true}, function(tabs){ varport=chrome.tabs.connect(//建立通道 tabs[0].id, {name:"yisheng"}//通道名称 ); });
在contentscripts或GoogleChrome扩展程序页面,监听建立连接的请求如下:
chrome.runtime.onConnect.addListener(function(port){ console.assert(port.name=="yisheng"); port.onMessage.addListener(function(msg){ if(msg.joke=="Knockknock") port.postMessage({question:"Who'sthere?"}); elseif(msg.answer=="Madame") port.postMessage({question:"Madamewho?"}); elseif(msg.answer=="Madame...Bovary") port.postMessage({question:"Idon'tgetit."}); }); });
在contentscripts或GoogleChrome扩展程序页面的任一端,调用chrome.runtime.Port.disconnect()则关闭连接,同时出发disconnect事件。这时,只有另一端监听chrome.runtime.Port.onDisconnect事件,则可以知道连接关闭。
3)GoogleChrome扩展程序之间消息模式
还可以在不同的GoogleChrome扩展程序之间发送消息,只要知道GoogleChrome扩展程序的ID。这使得GoogleChrome扩展程序可以发布服务为其他扩展程序所用。
这种GoogleChrome扩展程序之间的消息也分为一次性请求与响应模式和保持长期连接的模式。
GoogleChrome扩展程序监听调用其服务的消息如下:
//一次性请求与响应模式: chrome.runtime.onMessageExternal.addListener( function(request,sender,sendResponse){ if(sender.id==blacklistedExtension)//黑名单 return;//don'tallowthisextensionaccess elseif(request.getTargetData) sendResponse({targetData:targetData}); elseif(request.activateLasers){ varsuccess=activateLasers(); sendResponse({activateLasers:success}); } }); //保持长期连接的模式: chrome.runtime.onConnectExternal.addListener(function(port){ port.onMessage.addListener(function(msg){ //SeeotherexamplesforsampleonMessagehandlers. }); });
发送调用服务的消息如下:
//TheIDoftheextensionwewanttotalkto. varlaserExtensionId="abcdefghijklmnoabcdefhijklmnoabc"; //Makeasimplerequest: chrome.runtime.sendMessage(laserExtensionId,{getTargetData:true}, function(response){ if(targetInRange(response.targetData)) chrome.runtime.sendMessage(laserExtensionId,{activateLasers:true}); }); //Startalong-runningconversation: varport=chrome.runtime.connect(laserExtensionId); port.postMessage(...);
4)GoogleChrome扩展程序接收指定的Web页面发送的消息
GoogleChrome扩展程序可以与一些指定地点Web页面直接收发消息。
首先,在GoogleChrome扩展程序的manifest.json文件设置可以通信的Web页面范围:
"externally_connectable":{ "matches":["*://*.example.com/*"] }
其次,在GoogleChrome扩展程序中监听Web页面的消息如下:
chrome.runtime.onMessageExternal.addListener( function(request,sender,sendResponse){ if(sender.url==blacklistedWebsite) return;//don'tallowthiswebpageaccess if(request.openUrlInEditor) openUrl(request.openUrlInEditor); });
最后,在指定的Web页面中,发送消息如下:
//TheIDoftheextensionwewanttotalkto. vareditorExtensionId="abcdefghijklmnoabcdefhijklmnoabc"; //Makeasimplerequest: chrome.runtime.sendMessage(editorExtensionId,{openUrlInEditor:url}, function(response){ if(!response.success) handleError(url); });
相关文章推荐
- TCP/IP协议原理与应用笔记10:TCP/IP协议族
- 浅谈中国“无为”思想与项目管理
- spring事务隔离级别和传播行为
- nginx如何配置负载多个nodejs+socketio服务器
- Dictionary在多线程情况下
- Android学习之Activity
- cut用法
- linux下批量替换文件内容
- test9.9
- 2015年各国竞争力排名,中国领跑金砖国家
- 转载 C++的运算符重载
- openmeetings3.0.6 二次改动(无需源码)
- Android网络编程之URLConnection和HttpClient访问服务器
- C#编译器
- 乔布斯遗言
- 题目:《击鼓传花》
- uboot移植 --添加目标板(转载学习使用)
- 解决 veiw 之间 因为父view alpha 等于0 导致全部透明的问题
- 使用jQuery和css3实现了仿淘宝ued博客左边的菜单切换动画
- ttl-cmos