首先吐槽“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) {
      1. console.log(response.farewell);
        1. });
      1.  

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

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

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

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

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

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

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

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

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

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

                            manifest.json

                              1. {
                                1. "manifest_version": 2,
                                    1. "name": "Say Hello",
                                      1. "description": "This extension say hello to you.",
                                        1. "version": "1.0",
                                          1. "permissions": ["tabs", "<all_urls>"],
                                            1. "browser_action": {
                                              1. "default_icon": "icon.png",
                                                1. "default_popup": "popup.html"
                                                  1. },
                                                    1. "background": {
                                                      1. "page": "background.html"
                                                        1. },
                                                          1. "content_scripts": [{
                                                            1. "matches": ["<all_urls>"],
                                                              1. "js": ["contentscript.js"]
                                                                1. }]
                                                                  1. }
                                                                1.  

                                                                contentscript.js

                                                                  1. chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
                                                                    1. console.log(response.farewell);
                                                                      1. });
                                                                          1. chrome.runtime.onMessage.addListener(
                                                                            1. function(request, sender, sendResponse) {
                                                                              1. console.log(sender.tab ?
                                                                                1. "from a content script:" + sender.tab.url :
                                                                                  1. "from the extension");
                                                                                    1. if (request.greeting == "hello"){
                                                                                      1. sendResponse({farewell: "I'm contentscript,goodbye!"});
                                                                                        1. }
                                                                                          1. });
                                                                                        1.  

                                                                                        background.html

                                                                                          1. <!doctype html>
                                                                                            1. <html>
                                                                                              1. <head>
                                                                                                1. <title>
                                                                                                  1. Getting Started Extension's Popup
                                                                                                    1. </title>
                                                                                                      1. <script src="background.js">
                                                                                                        1. </script>
                                                                                                          1. </head>
                                                                                                            1. <body>
                                                                                                              1. <p>
                                                                                                                1. Hello!
                                                                                                                  1. </p>
                                                                                                                    1. <div id="r">
                                                                                                                      1. </div>
                                                                                                                        1. </body>
                                                                                                                            1. </html>
                                                                                                                          1.  

                                                                                                                          background.js

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

                                                                                                                                          popup.html

                                                                                                                                            1. <!doctype html>
                                                                                                                                              1. <html>
                                                                                                                                                1. <head>
                                                                                                                                                  1. <title>
                                                                                                                                                    1. Getting Started Extension's Popup
                                                                                                                                                      1. </title>
                                                                                                                                                        1. <script type="text/javascript" src="jquery.js">
                                                                                                                                                          1. </script>
                                                                                                                                                            1. <script src="popup.js">
                                                                                                                                                              1. </script>
                                                                                                                                                                1. </head>
                                                                                                                                                                  1. <body>
                                                                                                                                                                    1. <p>
                                                                                                                                                                      1. Hello!
                                                                                                                                                                        1. </p>
                                                                                                                                                                          1. <div id="r">
                                                                                                                                                                            1. </div>
                                                                                                                                                                              1. </body>
                                                                                                                                                                                  1. </html>
                                                                                                                                                                                1.  

                                                                                                                                                                                popup.js

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

                                                                                                                                                                                        参考资料

                                                                                                                                                                                        [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. 帝国cms-tab

                                                                                                                                                                                          <ul class="intro_commenTab"> [e:loop={"select classname,classpath,classid from ...

                                                                                                                                                                                        2. nginx_tcp模块集成到openresty(安装ngx_tcp_lua_module模块)

                                                                                                                                                                                          git地址:https://github.com/bigplum/nginx-tcp-lua-module openresty 本身是使用http协议进行通讯的, 但是项目中经常有要求输入是使用tcp ...

                                                                                                                                                                                        3. [LeetCode] 643. Maximum Average Subarray I_Easy tag: Dynamic Programming(Sliding windows)

                                                                                                                                                                                          Given an array consisting of n integers, find the contiguous subarray of given length k that has the ...

                                                                                                                                                                                        4. IntelliJ IDEA 配置tomcat 启动项目

                                                                                                                                                                                          1.打开file中setting中搜索Application Servers,如下图 2.添加服务器类型,例如tomcat,如下图,添加完成之后可以选定tomcat的目录,tomcat Home配置t ...

                                                                                                                                                                                        5. chrome debug 服务端性能

                                                                                                                                                                                          设置 http header 在 chrome 查看服务端性能 \Yii::$app->getResponse()->headers->set('Server-Timing', 'c ...

                                                                                                                                                                                        6. 隐藏apache服务器信息

                                                                                                                                                                                          安装完apache一般第一时间都是关闭apache的版本信息,黑客会通过apache暴露出来的信息针对性的入侵,为了服务器的安全这些信息一定要及时关闭. 1.隐藏PHP版本 修改php.ini exp ...

                                                                                                                                                                                        7. cocos2d JS 本地缓存存储登陆记住账号密码->相当于C++中的UserDefault

                                                                                                                                                                                          在cocos-js 3.0以上的版本中,当我们用到本地存储的时候,发现以前用到的UserDefault在JS中并没有导出,而是换成了LocalStorage. 在LocalStorage.h文件中我们 ...

                                                                                                                                                                                        8. cookie之三天免登录代码

                                                                                                                                                                                          LoginCookie.java 1 package com.bjsxt.cookie; import java.io.IOException; import java.net.URLDecoder; ...

                                                                                                                                                                                        9. 22.用demo通过点击切换图片路径

                                                                                                                                                                                          用demo通过点击切换图片路径 html: <img src="images/driving.png" class="driving"/> js: ...

                                                                                                                                                                                        10. linux 系统 cp: omitting directory 问题解决

                                                                                                                                                                                          在linux系统中复制文件夹时提示如下: cp: omitting directory `foldera/' 其中foldera是我要复制的文件夹名,出现该警告的原因是因为foldera目录下还存在目 ...