Chrome浏览器扩展开发系列之十三:消息传递Message
由于content scripts运行在Web页面的上下文中,属于Web页面的组成部分,而不是Google Chrome扩展程序。但是content scripts又往往需要与Google Chrome扩展程序的其他部分通信以共享数据。
这可以通过消息传递实现,通过彼此互相的消息的监听与反馈进行通信。一个消息可以包含任何有效的JSON对象,如null,boolean,number,string,array,object。
1) 一次性请求与响应模式
对于一次性请求与响应模式,chrome.runtime.sendMessage(obj, function(response){})是从content scripts发生请求消息给Google Chrome扩展程序页面。
从Google Chrome扩展程序页面发送请求消息给content scripts的时候,需要给出当前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 ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")//判断是否为要处理的消息
sendResponse({farewell: "goodbye"});
});
注意:如果为同一个消息注册了多个监听器,则只有第一个监听器能够调用sendResponse()方法,其他的监听器将被忽略。
2) 保持长期连接的模式
对于保持长期连接的模式,在content scripts与Chrome扩展程序页面之间建立通道(可以为通道命名),可以处理多个消息。在通道的两端分别拥有一个chrome.runtime.Port对象,用以收发消息。
在content scripts主动建立通道如下:
var port = chrome.runtime.connect({name: "yisheng"});//通道名称
port.postMessage({joke: "Knock knock"});//发送消息
port.onMessage.addListener(function(msg) {//监听消息
if (msg.question == "Who's there?")
port.postMessage({answer: "yisheng"});
else if (msg.question == "Madame who?")
port.postMessage({answer: "Madame... Bovary"});
});
在Google Chrome扩展程序页面主动建立通道如下:
chrome.tabs.query(
{active: true, currentWindow: true},
function(tabs) {
var port = chrome.tabs.connect(//建立通道
tabs[0].id,
{name: "yisheng"}//通道名称
);
});
在content scripts或Google Chrome扩展程序页面,监听建立连接的请求如下:
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "yisheng");
port.onMessage.addListener(function(msg) {
if (msg.joke == "Knock knock")
port.postMessage({question: "Who's there?"});
else if (msg.answer == "Madame")
port.postMessage({question: "Madame who?"});
else if (msg.answer == "Madame... Bovary")
port.postMessage({question: "I don't get it."});
});
});
在content scripts或Google Chrome扩展程序页面的任一端,调用chrome.runtime.Port.disconnect()则关闭连接,同时出发disconnect事件。这时,只有另一端监听chrome.runtime.Port.onDisconnect事件,则可以知道连接关闭。
3) Google Chrome扩展程序之间消息模式
还可以在不同的Google Chrome扩展程序之间发送消息,只要知道Google Chrome扩展程序的ID。这使得Google Chrome扩展程序可以发布服务为其他扩展程序所用。
这种Google Chrome扩展程序之间的消息也分为一次性请求与响应模式和保持长期连接的模式。
Google Chrome扩展程序监听调用其服务的消息如下:
//一次性请求与响应模式:
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (sender.id == blacklistedExtension)//黑名单
return; // don't allow this extension access
else if (request.getTargetData)
sendResponse({targetData: targetData});
else if (request.activateLasers) {
var success = activateLasers();
sendResponse({activateLasers: success});
}
}); //保持长期连接的模式:
chrome.runtime.onConnectExternal.addListener(function(port) {
port.onMessage.addListener(function(msg) {
// See other examples for sample onMessage handlers.
});
});
发送调用服务的消息如下:
// The ID of the extension we want to talk to.
var laserExtensionId = "abcdefghijklmnoabcdefhijklmnoabc"; // Make a simple request:
chrome.runtime.sendMessage(laserExtensionId, {getTargetData: true},
function(response) {
if (targetInRange(response.targetData))
chrome.runtime.sendMessage(laserExtensionId, {activateLasers: true});
}); // Start a long-running conversation:
var port = chrome.runtime.connect(laserExtensionId);
port.postMessage(...);
4) Google Chrome扩展程序接收指定的Web页面发送的消息
Google Chrome扩展程序可以与一些指定地点Web页面直接收发消息。
首先,在Google Chrome扩展程序的manifest.json文件设置可以通信的Web页面范围:
"externally_connectable": {
"matches": ["*://*.example.com/*"]
}
其次,在Google Chrome扩展程序中监听Web页面的消息如下:
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (sender.url == blacklistedWebsite)
return; // don't allow this web page access
if (request.openUrlInEditor)
openUrl(request.openUrlInEditor);
});
最后,在指定的Web页面中,发送消息如下:
// The ID of the extension we want to talk to.
var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc"; // Make a simple request:
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
function(response) {
if (!response.success)
handleError(url);
});
Chrome浏览器扩展开发系列之十三:消息传递Message的更多相关文章
- Chrome浏览器扩展开发系列之十四:本地消息机制Native messagin
Chrome浏览器扩展开发系列之十四:本地消息机制Native messaging 2016-11-24 09:36 114人阅读 评论(0) 收藏 举报 分类: PPAPI(27) 通过将浏览器 ...
- Chrome浏览器扩展开发系列之十四
Chrome浏览器扩展开发系列之十四:本地消息机制Native messaging 时间:2015-10-08 16:17:59 阅读:1361 评论:0 收藏:0 ...
- Chrome浏览器扩展开发系列之十八:扩展的软件国际化chrome.i18n API
i18n是internationalization 的简写,这里将讨论软件国际化的问题.熟悉软件国际化的朋友应该知道,软件国际化要求,页面中所有用户可见的字符串都必须置于资源属性文件中.资源属性文件中 ...
- Chrome浏览器扩展开发系列之十九:扩展开发示例
翻译总结了这么多的官网内容,下面以一款博主开发的“沪深股票价格变化实时追踪提醒”软件为例,介绍Chrome浏览器扩展程序的开发,开发环境为Eclipse IDE+Chrome Browser. “沪深 ...
- Chrome浏览器扩展开发系列之十六:扩展中可用的Chrome浏览器API
除了Chrome浏览器支持的chrome.* API之外,Chrome浏览器扩展还可以使用Chrome浏览器为Web页面或Chrome app提供的APIs.对于Chrome浏览器2支持的API,还可 ...
- Chrome浏览器扩展开发系列之十二:Content Scripts
Content Scripts是运行在Web页面的上下文的JavaScript文件.通过标准的DOM,Content Scripts 可以操作(读取并修改)浏览器当前访问的Web页面的内容. Cont ...
- Chrome浏览器扩展开发系列之十一:NPAPI插件的使用
在Chrome浏览器扩展中使用HTML和JavaScript非常容易,但是如何重用已有的非JavaScript遗留系统代码呢?答案是将NPAPI插件绑定到Chrome浏览器扩展,从而实现在Chrome ...
- Chrome浏览器扩展开发系列之十七:扩展中可用的chrome.events API
chrome.events中定义了一些常见的事件类型,可以供Chrome浏览器扩展程序发出对应的事件对象. 对于关注的事件,首先要通过addListener()在对应的事件上注册监听器,示例如下: c ...
- Chrome浏览器扩展开发系列之十五:跨域访问的XMLHttpRequest对象
XMLHttpRequest对象是W3C的标准API,用于访问服务器资源.XMLHttpRequest对象支持多种文本格式,如XML和JSON等.XMLHttpRequest对象可以通过HTTP和HT ...
随机推荐
- 使用redis做mybaties的二级缓存(2)-Mybatis 二级缓存小心使用
Mybatis默认对二级缓存是关闭的,一级缓存默认开启: 下面就说说为什么使用二级缓存需要注意: 二级缓存是建立在同一个namespace下的,如果对表的操作查询可能有多个namespace,那么得到 ...
- Spring Security教程系列(一)基础篇-1
第 1 章 一个简单的HelloWorld 第 1 章 一个简单的HelloWorld Spring Security中可以使用Acegi-1.x时代的普通配置方式,也可以使用从2.0时代才出现的命名 ...
- org.apache.commons.lang下的工具类
1.org.apache.commons.lang.ArrayUtils 例子 package chongqingyusp; import java.util.Map; import org.apac ...
- Sqoop简介及安装
Hadoop业务的大致开发流程以及Sqoop在业务中的地位: Sqoop概念 Sqoop可以理解为[SQL–to–Hadoop],正如名字所示,Sqoop是一个用来将关系型数据库和Hadoop中的数据 ...
- java实现文件批量导入导出实例(兼容xls,xlsx)
1.介绍 java实现文件的导入导出数据库,目前在大部分系统中是比较常见的功能了,今天写个小demo来理解其原理,没接触过的同学也可以看看参考下. 目前我所接触过的导入导出技术主要有POI和iRepo ...
- Java经典编程题50道之三十三
打印出杨辉三角形(要求打印出10行如下图)11 11 2 11 3 3 11 4 6 4 11 5 10 10 5 1 public class Example33 { public static v ...
- 最基础的mybatis入门demo
demo结构 数据库情况 (不会转sql语句 骚瑞) 数据库连接信息 jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:m ...
- lucene全文搜索之四:创建索引搜索器、6种文档搜索器实现以及搜索结果分析(结合IKAnalyzer分词器的搜索器)基于lucene5.5.3
前言: 前面几章已经很详细的讲解了如何创建索引器对索引进行增删查(没有更新操作).如何管理索引目录以及如何使用分词器,上一章讲解了如何生成索引字段和创建索引文档,并把创建的索引文档保存到索引目录,到这 ...
- C语言和go语言之间的交互
一.go代码中使用C代码 go代码中使用C代码,在go语言的函数块中,以注释的方式写入C代码,然后紧跟import "C" 即可在go代码中使用C函数 代码示例: go代码:tes ...
- Cordova各个插件使用介绍系列(二)—$cordovaBarcodeScanner扫描二维码与生成二维码
详情链接地址:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/cordova-2-cordovabarcodescanner/ 这是 ...