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 ...
随机推荐
- 基于Android的上课助手的概况及第一周冲刺详情
基于Android平台的上课助手 一. 功能简介 课表查询 课程提醒 空闲教室的查询 二. 开发环境 Android 三. 开发成员 组长:李志岩 成员:王亚蕊.孙 ...
- ionic 使用mobisscrolls,实现日期选择的插件
废话不多说,直接说用法: 1,先下载mobisscrolls的破解版,下载地址,链接:http://pan.baidu.com/s/1boSKf51 密码:5dft 当然你也可以去官网下载,不过官网的 ...
- 小程序地图map
wxml: <button class="button" bindtap="getlocation" style="margin-top:30p ...
- 使用 libdvm.so 内部函数dvm* 加载 dex
首先要清楚,odex只是对代码段(我将dex文件与elf文件类比,大家都将执行文件分成不同的段)作优化,而其它用于类反射信息的段都应用原来的dex,所以odex文件内部还包含了一个dex. 打开一个d ...
- 【转】Delphi多线程编程
文章来源: http://liukun966123.my.gsdn.net/2004/10/22/4797/ Delphi中有一个线程类TThread是用来实现多线程编程的,这个绝大多数Delphi书 ...
- 向EXECL文件中导入数据的同时插入图片
因为项目需要在导出数据到EXECL文档的同时还需要导出图片进去,在处理是遇到的一些问题,在此记录一下. 首先代码写好之后放测试服务器上去执行的时候报错了,报检索 COM 类工厂中 CLSID 为 {0 ...
- 关于combotree的用法总结
后台: 实体树 public class TreeNode{ private String id; private String text; private String level; private ...
- JS中的函数传参
前言: 函数分为有参有返回值,有参无返回值,无参无返回值,无参有返回值:那么对于无参数的函数你想使用函数的调用怎么办呢?如果你想封装一个代码,实现多种功能,但是形参大于实参或者实参大于形参又该如何?本 ...
- Python 的枚举 Enum
枚举是常用的功能,看看Python的枚举. from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May' ...
- 关于angular-route后获取路由标签的一些问题
要实现angular路由,我们需要用到angular.js和angular-route.js 在接入网络的情况下,很多网站都可以下载到这个文件. 然后呢,将文件引入到你的HTML中,然后是基础格式 h ...