由于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的更多相关文章

  1. Chrome浏览器扩展开发系列之十四:本地消息机制Native messagin

    Chrome浏览器扩展开发系列之十四:本地消息机制Native messaging 2016-11-24 09:36 114人阅读 评论(0) 收藏 举报  分类: PPAPI(27)  通过将浏览器 ...

  2. Chrome浏览器扩展开发系列之十四

    Chrome浏览器扩展开发系列之十四:本地消息机制Native messaging 时间:2015-10-08 16:17:59      阅读:1361      评论:0      收藏:0    ...

  3. Chrome浏览器扩展开发系列之十八:扩展的软件国际化chrome.i18n API

    i18n是internationalization 的简写,这里将讨论软件国际化的问题.熟悉软件国际化的朋友应该知道,软件国际化要求,页面中所有用户可见的字符串都必须置于资源属性文件中.资源属性文件中 ...

  4. Chrome浏览器扩展开发系列之十九:扩展开发示例

    翻译总结了这么多的官网内容,下面以一款博主开发的“沪深股票价格变化实时追踪提醒”软件为例,介绍Chrome浏览器扩展程序的开发,开发环境为Eclipse IDE+Chrome Browser. “沪深 ...

  5. Chrome浏览器扩展开发系列之十六:扩展中可用的Chrome浏览器API

    除了Chrome浏览器支持的chrome.* API之外,Chrome浏览器扩展还可以使用Chrome浏览器为Web页面或Chrome app提供的APIs.对于Chrome浏览器2支持的API,还可 ...

  6. Chrome浏览器扩展开发系列之十二:Content Scripts

    Content Scripts是运行在Web页面的上下文的JavaScript文件.通过标准的DOM,Content Scripts 可以操作(读取并修改)浏览器当前访问的Web页面的内容. Cont ...

  7. Chrome浏览器扩展开发系列之十一:NPAPI插件的使用

    在Chrome浏览器扩展中使用HTML和JavaScript非常容易,但是如何重用已有的非JavaScript遗留系统代码呢?答案是将NPAPI插件绑定到Chrome浏览器扩展,从而实现在Chrome ...

  8. Chrome浏览器扩展开发系列之十七:扩展中可用的chrome.events API

    chrome.events中定义了一些常见的事件类型,可以供Chrome浏览器扩展程序发出对应的事件对象. 对于关注的事件,首先要通过addListener()在对应的事件上注册监听器,示例如下: c ...

  9. Chrome浏览器扩展开发系列之十五:跨域访问的XMLHttpRequest对象

    XMLHttpRequest对象是W3C的标准API,用于访问服务器资源.XMLHttpRequest对象支持多种文本格式,如XML和JSON等.XMLHttpRequest对象可以通过HTTP和HT ...

随机推荐

  1. 把ipad作为电脑的第二显示器

    需要:1,iPad          2,ios端需要软件idisplay(在pp助手里搜索idisplay下载即可)       3,windows需要软件iDisplay(链接http://www ...

  2. java虚拟机学习-JVM调优总结-分代垃圾回收详述(9)

    为什么要分代 分代的垃圾回收策略,是基于这样一个事实:不同的对象的生命周期是不一样的.因此,不同生命周期的对象可以采取不同的收集方式,以便提高回收效率. 在Java程序运行的过程中,会产生大量的对象, ...

  3. 一、 开篇(ASP.NET MVC5 系列)

    这个教程将教你一些用VS2013创建ASP.NET MVC 5 Web应用程序基础知识.为了避免开发工具的不一致而带来的一些小麻烦,建议你使用和我一样的开发工具VS2013英文版. 开发工具:Visu ...

  4. Include promo/activity effect into the prediction (extended ARIMA model with R)

    I want to consider an approach of forecasting I really like and frequently use. It allows to include ...

  5. Apache许可翻译

    https://www.apache.org/licenses/LICENSE-2.0 Apache许可 2.0 2004.1 使用.复制和发行的术语和条件. 1 定义 "License&q ...

  6. vue+vux+axios+vuex+vue-router的项目的理解

    本文主要是讲解项目前期的工作,后期考虑再详细说明. 作为一个技术团队如果你们团队选择了上面的技术栈,这说明你们的技术团体对于vue有很熟练的掌握了.在这里我想说明的是前期架构的重要.这里有一遍博客写的 ...

  7. 最近用django做了个在线数据分析小网站

    用最近做的理赔申请人测试数据集做了个在线分析小网站. 数据结构,算法等设置都保存在json文件里.将来对这个小破站扩充算法,只修改一下json文件就行. 当然,结果分析还是要加代码的.页面代码不贴了, ...

  8. poj2069

    poj2069 题意 求一个覆盖所有点的最小球体的半径.即求空间内一点到所有点的距离的最大值最小的点. 分析 模拟退火算法,但这道题竟然不用随机函数就能过了,主要体现了算法的渐近收敛性, 起始点随意取 ...

  9. 一天搞定CSS: overflow--14

    overflow:针对超出父级的内容如何显示 代码演示 <!DOCTYPE html> <html> <head> <meta charset="U ...

  10. PHP版本替换, phpinfo和php -v显示版本信息不一致

    环境:OS X EI Capitan 10.11 & lnmp 背景: 1想将lamp(xampp安装的,php5.2)换成 lnmp(php7.0)   2php5.2卸载(xampp卸载& ...