首先吐槽“360极速浏览器应用开发平台”的开发文档,在消息传递(http://open.chrome.360.cn/extension_dev/messaging.html)一节中,翻译极其低劣:

Sending a request from the extension to a content script looks very similar, except
that you need to specify which tab to send it to. This example demonstrates sending a message to the content script in the selected tab.

传递一个请求到扩展很容易,你需要指定哪个标签发起这个请求。下面这个例子展示了如何指定标签发起一个请求。

similar翻译成容易,发送到tab翻译成标签发起。

代码更新也不及时,chrome.tabs.getSelected和chrome.extension.sendRequest这两个函数在新版Chrome已经废弃(参考资料[1])。

学习过程中偷懒不看英文,结果反而被绕个大圈子。

1、开发文档

Chrome的消息传递,可以在Web(通过content script)和扩展之间进行,任意一方都可发送或接收消息。

Web(通过content
script)发送消息如下:


  1. chrome.runtime.sendMessage({greeting: “hello”}, function(response) {
  2. console.log(response.farewell);
  3. });

通过chrome.runtime.sendMessage函数发送消息,其中{greeting: “hello”}是消息对象(大括号的用法见参考资料[2]);function(response) {…}是回调函数,处理接收方发回的消息。

插件发送消息需要确定接收的Tab,如下:


  1. chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  2. chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
  3. console.log(response.farewell);
  4. });
  5. });

以上代码指定当前tab为消息的接收者。

接受端需要通过runtime.onMessage事件处理消息:


  1. chrome.runtime.onMessage.addListener(
  2. function(request, sender, sendResponse) {
  3. console.log(sender.tab ?
  4. "from a content script:" + sender.tab.url :
  5. "from the extension");
  6. if (request.greeting == "hello")
  7. sendResponse({farewell: "goodbye"});
  8. });

事件处理通过function(request, sender, sendResponse){…}完成,以上代码处理消息时在控制台记录发送者的消息,回复“goodbye”消息。

2、完整示例
示例完成content script和插件的消息传递,具体包括:

1、content script发送消息,backgroud接收消息;

2、popup发送消息,content script接收消息。

manifest.json


  1. {
  2. "manifest_version": 2,
  3. "name": "Say Hello",
  4. "description": "This extension say hello to you.",
  5. "version": "1.0",
  6. "permissions": ["tabs", "<all_urls>"],
  7. "browser_action": {
  8. "default_icon": "icon.png",
  9. "default_popup": "popup.html"
  10. },
  11. "background": {
  12. "page": "background.html"
  13. },
  14. "content_scripts": [{
  15. "matches": ["<all_urls>"],
  16. "js": ["contentscript.js"]
  17. }]
  18. }

contentscript.js


  1. chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  2. console.log(response.farewell);
  3. });
  4. chrome.runtime.onMessage.addListener(
  5. function(request, sender, sendResponse) {
  6. console.log(sender.tab ?
  7. "from a content script:" + sender.tab.url :
  8. "from the extension");
  9. if (request.greeting == "hello"){
  10. sendResponse({farewell: "I'm contentscript,goodbye!"});
  11. }
  12. });

background.html


  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>
  5. Getting Started Extension's Popup
  6. </title>
  7. <script src="background.js">
  8. </script>
  9. </head>
  10. <body>
  11. <p>
  12. Hello!
  13. </p>
  14. <div id="r">
  15. </div>
  16. </body>
  17. </html>

background.js


  1. chrome.runtime.onMessage.addListener(
  2. function(request, sender, sendResponse) {
  3. console.log(sender.tab ?
  4. "from a content script:" + sender.tab.url :
  5. "from the extension");
  6. if (request.greeting == "hello")
  7. sendResponse({farewell: "I'm backgroud,goodbye!"});
  8. });

popup.html


  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>
  5. Getting Started Extension's Popup
  6. </title>
  7. <script type="text/javascript" src="jquery.js">
  8. </script>
  9. <script src="popup.js">
  10. </script>
  11. </head>
  12. <body>
  13. <p>
  14. Hello!
  15. </p>
  16. <div id="r">
  17. </div>
  18. </body>
  19. </html>

popup.js


  1. chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  2. chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
  3. console.log(response.farewell);
  4. });
  5. });

参考资料

[1]Content脚本与扩展的其他页面脚本的消息传递http://blog.csdn.net/greatpresident/article/details/9052801

[2]Javascript中大括号“{}”的多义性http://www.cnblogs.com/snandy/archive/2011/02/28/1966894.html

Chrome插件消息传递实例的更多相关文章

  1. 利用chrome插件批量读取浏览器页面内容并写入数据库

    试想一下,如果每天要收集100页网页数据甚至更多.如果采用人工收集会吐血,用程序去收集也就成为一个不二的选择.首先肯定会想到说用java.php.C#等高级语言,但这偏偏又有个登陆和验证码,搞到无所适 ...

  2. 微软专家推荐11个Chrome 插件

    Web开发人员,需要长时间使用浏览器,尽管Windows10 Edge浏览器启动非常快速,且支持110多种设备,Edge支持基于JS 扩展,但也删除了很多旧功能像Active-X等插件.多数情况下,插 ...

  3. 我的项目:一个chrome插件的诞生记,名字叫jumper

    选课是个问题,为了选课,便有了以下的故事. 最开始,萌生想法于2013年7月. 接着网上了解了chrome的结构知识,却发现例子是假的. 幸好有之前师兄的一个同功能插件开源,但代码写得很乱,我喜欢逻辑 ...

  4. Chrome插件Visual Event查看Dom元素绑定事件的利器

    找这工具找了好久,统一找着了,开发人员不可多得的好东东,收藏做一下分享. 用Chrome插件Visual Event查看Dom绑定的事件 Visual Event简介 Visual Event是一个开 ...

  5. 【干货】Chrome插件(扩展)开发全攻略(不点进来看看你肯定后悔)

    写在前面 我花了将近一个多月的时间断断续续写下这篇博文,并精心写下完整demo,写博客的辛苦大家懂的,所以转载务必保留出处.本文所有涉及到的大部分代码均在这个demo里面:https://github ...

  6. 【干货】Chrome插件(扩展)开发全攻略

    写在前面 我花了将近一个多月的时间断断续续写下这篇博文,并精心写下完整demo,写博客的辛苦大家懂的,所以转载务必保留出处.本文所有涉及到的大部分代码均在这个demo里面:https://github ...

  7. 2018-10-31 在线代码离线翻译Chrome插件"一马"v0.0.8

    续前文: Chrome插件实现GitHub代码离线翻译v0.0.4 添加了对"码云"在线代码的翻译支持, 因此改名暂为"一马". 在此贴中调研了常用的在线代码网 ...

  8. chrome 浏览器插件开发(一)—— 创建第一个chrome插件

    最近在开发一个chrome插件,在网上找到了一些的文章,虽说按照文章可以写出对应的例子,但若要进行实际开发,发现还是有不少文章中没有的坑.下面我将结合我在开发过程中遇到的几个方面,对这些坑做一下补充. ...

  9. Chrome插件(扩展)

    [干货]Chrome插件(扩展)开发全攻略   写在前面 我花了将近一个多月的时间断断续续写下这篇博文,并精心写下完整demo,写博客的辛苦大家懂的,所以转载务必保留出处.本文所有涉及到的大部分代码均 ...

随机推荐

  1. Python识别字符型图片验证码

    前言 验证码是目前互联网上非常常见也是非常重要的一个事物,充当着很多系统的 防火墙 功能,但是随时OCR技术的发展,验证码暴露出来的安全问题也越来越严峻.本文介绍了一套字符验证码识别的完整流程,对于验 ...

  2. chmod a+r file:给所有用户添加读的权限

    chmod a+r *:用户自己使用此命令,柯给所有用户添加可读的权限 超级用户给其他用户设置权限:sudo chmod a+rx /home/user   使所有人可以访问,读取文件,bu no W ...

  3. NYOJ 最长公共子序列

    # include<iostream> # include<string> # include<stdio.h> using namespace std; ][]; ...

  4. 敏捷开发— —Scrum 学习笔记

    敏捷开发模式是一种从1990年代开始逐渐引起广泛关注的一些新型软件开发方法,是一种应对快速变化的需求的一种软件开发能力.它们的具体名称.理念.过程.术语都不尽相同,相对于"非敏捷" ...

  5. HTML5-CSS3-JavaScript(1)

    之前大致总结过HTML5的发展. 这里贴出之前的随笔:http://www.cnblogs.com/jiangxiaobo/p/5199924.html 我们就从HTML5的基础总结起.希望可以提高自 ...

  6. content_type

    1.作用 将app名称与其中表关系进行保存 在models创建表时,关联到ContentType并不会产生实际的字段 2.使用 在models中代码 from django.db import mod ...

  7. java面试中经常会被问到分布式面试题

    1.Dubbo的底层实现原理和机制 –高性能和透明化的RPC远程服务调用方案 –SOA服务治理方案 Dubbo缺省协议采用单一长连接和NIO异步通讯, 适合于小数据量大并发的服务调用,以及服务消费者机 ...

  8. 深入解密.NET(GC垃圾回收)

    值类型与引用类型 值类型(Value Type),值类型实例通常分配在线程的堆栈(stack)上,并且不包含任何指向实例数据的指针,因为变量本身就包含了其实例数据 C#的所有值类型均隐式派生自Syst ...

  9. ssh生成私钥

    指定证书类型为rsa ssh-keygen.exe  -t rsa https://www.cnblogs.com/pixy/p/4722381.html

  10. 根据异常自定义处理逻辑(【附】java异常处理规范)

    ▄︻┻┳═一『异常捕获系列』Agenda: ▄︻┻┳═一有关于异常捕获点滴,plus我也揭揭java的短 ▄︻┻┳═一根据异常自定义处理逻辑([附]java异常处理规范) ▄︻┻┳═一利用自定义异常来 ...