Chrome插件消息传递实例
首先吐槽“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)发送消息如下:
chrome.runtime.sendMessage({greeting: “hello”}, function(response) {
console.log(response.farewell);
});
通过chrome.runtime.sendMessage函数发送消息,其中{greeting: “hello”}是消息对象(大括号的用法见参考资料[2]);function(response) {…}是回调函数,处理接收方发回的消息。
插件发送消息需要确定接收的Tab,如下:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
以上代码指定当前tab为消息的接收者。
接受端需要通过runtime.onMessage事件处理消息:
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"});
});
事件处理通过function(request, sender, sendResponse){…}完成,以上代码处理消息时在控制台记录发送者的消息,回复“goodbye”消息。
2、完整示例
示例完成content script和插件的消息传递,具体包括:
1、content script发送消息,backgroud接收消息;
2、popup发送消息,content script接收消息。
manifest.json
{
"manifest_version": 2,
"name": "Say Hello",
"description": "This extension say hello to you.",
"version": "1.0",
"permissions": ["tabs", "<all_urls>"],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"page": "background.html"
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["contentscript.js"]
}]
}
contentscript.js
chrome.runtime.sendMessage({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: "I'm contentscript,goodbye!"});
}
});
background.html
<!doctype html>
<html>
<head>
<title>
Getting Started Extension's Popup
</title>
<script src="background.js">
</script>
</head>
<body>
<p>
Hello!
</p>
<div id="r">
</div>
</body>
</html>
background.js
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: "I'm backgroud,goodbye!"});
});
popup.html
<!doctype html>
<html>
<head>
<title>
Getting Started Extension's Popup
</title>
<script type="text/javascript" src="jquery.js">
</script>
<script src="popup.js">
</script>
</head>
<body>
<p>
Hello!
</p>
<div id="r">
</div>
</body>
</html>
popup.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
参考资料
[1]Content脚本与扩展的其他页面脚本的消息传递http://blog.csdn.net/greatpresident/article/details/9052801
[2]Javascript中大括号“{}”的多义性http://www.cnblogs.com/snandy/archive/2011/02/28/1966894.html
Chrome插件消息传递实例的更多相关文章
- 利用chrome插件批量读取浏览器页面内容并写入数据库
		试想一下,如果每天要收集100页网页数据甚至更多.如果采用人工收集会吐血,用程序去收集也就成为一个不二的选择.首先肯定会想到说用java.php.C#等高级语言,但这偏偏又有个登陆和验证码,搞到无所适 ... 
- 微软专家推荐11个Chrome 插件
		Web开发人员,需要长时间使用浏览器,尽管Windows10 Edge浏览器启动非常快速,且支持110多种设备,Edge支持基于JS 扩展,但也删除了很多旧功能像Active-X等插件.多数情况下,插 ... 
- 我的项目:一个chrome插件的诞生记,名字叫jumper
		选课是个问题,为了选课,便有了以下的故事. 最开始,萌生想法于2013年7月. 接着网上了解了chrome的结构知识,却发现例子是假的. 幸好有之前师兄的一个同功能插件开源,但代码写得很乱,我喜欢逻辑 ... 
- Chrome插件Visual Event查看Dom元素绑定事件的利器
		找这工具找了好久,统一找着了,开发人员不可多得的好东东,收藏做一下分享. 用Chrome插件Visual Event查看Dom绑定的事件 Visual Event简介 Visual Event是一个开 ... 
- 【干货】Chrome插件(扩展)开发全攻略(不点进来看看你肯定后悔)
		写在前面 我花了将近一个多月的时间断断续续写下这篇博文,并精心写下完整demo,写博客的辛苦大家懂的,所以转载务必保留出处.本文所有涉及到的大部分代码均在这个demo里面:https://github ... 
- 【干货】Chrome插件(扩展)开发全攻略
		写在前面 我花了将近一个多月的时间断断续续写下这篇博文,并精心写下完整demo,写博客的辛苦大家懂的,所以转载务必保留出处.本文所有涉及到的大部分代码均在这个demo里面:https://github ... 
- 2018-10-31 在线代码离线翻译Chrome插件"一马"v0.0.8
		续前文: Chrome插件实现GitHub代码离线翻译v0.0.4 添加了对"码云"在线代码的翻译支持, 因此改名暂为"一马". 在此贴中调研了常用的在线代码网 ... 
- chrome 浏览器插件开发(一)—— 创建第一个chrome插件
		最近在开发一个chrome插件,在网上找到了一些的文章,虽说按照文章可以写出对应的例子,但若要进行实际开发,发现还是有不少文章中没有的坑.下面我将结合我在开发过程中遇到的几个方面,对这些坑做一下补充. ... 
- Chrome插件(扩展)
		[干货]Chrome插件(扩展)开发全攻略 写在前面 我花了将近一个多月的时间断断续续写下这篇博文,并精心写下完整demo,写博客的辛苦大家懂的,所以转载务必保留出处.本文所有涉及到的大部分代码均 ... 
随机推荐
- 报错解决——OSError: libdarknet.so: cannot open shared object file: No such file or directory
			在python目录下打开终端,输入 python darknet.py 结果报错 Traceback (most recent call last): File “darknet.py”, line ... 
- 003-RFC关于媒体类型说明
			一.概述 RFC-822 Standard for ARPA Internet text messages [ARPA互连网文本信息标准]RFC-2045 MIME Part 1: Format ... 
- Redis入门到高可用(七)——Hash
			一.结构 Mapmap结构: filed 不能相同,value可以相同. 二.重要指令 ♦️ HSET ♦️ HGET ♦️ HDEL ♦️ Hlen ♦️ HEXISTS ♦️HGETALL ... 
- 20165236  《Java程序设计》第七周学习总结
			20165236 <Java程序设计>第七周学习总结 教材学习内容总结 第十一章 JDBC与MySQL数据库 1.MySQL数据库管理系统: MySQL数据库管理系统,简称MySQL,是 ... 
- 两种ps切图方法(图层/切片)
			两种Ps切图方法 一. 基础操作: a) Ctrl++ 放大图片,ctrl - -缩小图片 b) 按住空格键space+,点击鼠标左键,拖动图片. c) 修改单位,点击编辑 ... 
- 创建genil component
			1: 创建一个类继承 CL_WCF_GENIL_ABSTR_COMPONENT 2:创建 genil _ editor 创建 component, 填入该实现类. 3: genil component ... 
- Pycharm增加新安装Python的路径
			Pycharm默认的Python是python2,但是如果代码是python3写的,就需要在pycharm里的project interpreter增加python3 注意,一定要找到Project ... 
- 函数 return
			return 的作用 一.返回一个值给函数,主函数调用这个函数后能得到这个返回的值.二.结束函数,例如你运行到一个地方,虽然后面还有代码但是你不想再继续运行,这时就可以直接用 return:这条语句来 ... 
- leetcode 198打家劫舍
			讲解视频见刘宇波leetcode动态规划第三个视频 记忆化搜索代码: #include <bits/stdc++.h> using namespace std; class Solutio ... 
- iOS UI基础-15.0 UIWebView
			WebView介绍 知识点: 代码创建一个UIWebView OC调用html的js js页面调用OC 相关代码实现 代码创建一个UIWebView // 1.webView UIWebView *w ... 
