Chrome Extension sendMessage & sendRequest【谷歌浏览器扩展之消息通信】
来源:互联网 发布:资源商城源码 编辑:程序博客网 时间:2024/06/07 03:16
嗯,标题不是翻译。
简言 content_scripts 在浏览的网页中运行(注入),background & options_page 在应用里运行,但 content_scripts 可与应用通信,窗体的交互参考前面提供的文档或官方的图和介绍这里不赘述。
前后台消息通信,刚开始接触时使用一些文档中提供的方法用不了。前后台的发送、接收消息的方式不同,长连接参考开发文档(文档中有的发送方式已不能使用了,下面的可用):
从 content_scripts 发送消息或处理的数据发送给 background 时:
//content_scripts 发送消息给 background var oimgs = document.getElementsByTagName('img');chrome.runtime.sendMessage({msg: 'send', imgs: oimgs}, function(response) {if(response){ //使用 response.status 如果返回的数据为空或不存在此值会报错//alert('完成');}});
background 接收来自 content_scripts 的消息
//background 接受来自 contentscript 的消息var ocurTabId;chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { //console.log(sender.tab ? "来自内容脚本:" + sender.tab.url : "来自应用");ocurTabId = sender.tab.id; //消息来自哪个标签页的ID,记录这个值下面有用 if (request.imgs){var _imgSplit, _dirName = '', _imgName = '', _imgSuffix = '', srand = Math.random() + '';for(var i=0; i<request.imgs.length; i++){_imgSplit = request.imgs[i].img.split('/');_imgName = _imgSplit.pop();if(!_dirName){_dirName = request.imgs[i].name ? request.imgs[i].name.replace(/[\s*\?\,\:\;\'\"\.\/\\\#\!\@\`\*\^\%\$\|]*/g, '') : srand.substr(2);}//_imgSuffix = _imgName.split('.').pop();console.log( _dirName +'/'+ _imgName );}sendResponse({status: 200}); //回复}else{sendResponse({status: 0});}});
从 background 发送消息给 content_scripts 时:
//从后台发送消息给前端需要指定 tabId,前端发消息来时有这个值chrome.tabs.sendRequest(ocurTabId, {msg: 'finished'}, function(response) {console.log(response);});
content_scripts 接受来自 background 的消息:
//content_scripts 接受来自 background 的消息chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {console.log(sender.tab ? "来自内容脚本:" + sender.tab.url : "来自应用");sendResponse({status: 200});if(request.msg == 'finished'){setTimeout(function(){window.location.reload();}, 300);}else{alert('失败');}});
阅读全文
0 0
- Chrome Extension sendMessage & sendRequest【谷歌浏览器扩展之消息通信】
- Chrome Extension manifest【谷歌浏览器扩展之配置】
- Chrome Extension options_page & storage【谷歌浏览器扩展之选项页和storage】
- Chrome Extension Ajax & downloads【谷歌浏览器扩展之Ajax和下载】
- Chrome Extension notifications【谷歌浏览器扩展之弹窗通知】
- Chrome浏览器扩展开发系列之十三:消息传递Message
- Chrome 浏览器 extension 指南
- Chrome浏览器扩展开发系列之十四:本地消息机制Native messaging
- Chrome 扩展开发之消息传递
- chrome扩展开发之消息传递
- Chrome浏览器扩展学习之 - 添加书签
- VC进程间通信之消息传递PostMessge()或SendMessage()
- 谷歌浏览器插件 离线安装 AXURE RP EXTENSION For Chrome
- 下载谷歌浏览器(Chrome)扩展crx文件
- chrome 谷歌浏览器怎么添加Axure扩展
- Chrome浏览器扩展开发系列之十九:扩展开发示例
- Chrome浏览器扩展开发系列之二:Google Chrome浏览器扩展的调试
- Chrome浏览器扩展开发系列之三:Google Chrome浏览器扩展的架构
- js初级脚本算法
- 学习java的杂乱笔记
- Windows下的简单命令行
- android模仿微信相册多选。预览,删除
- Android应用开发—RecyclerView绘制蒙层
- Chrome Extension sendMessage & sendRequest【谷歌浏览器扩展之消息通信】
- 集合框架复习总结(三)
- Gradle 入门到精通(四)
- 插入排序(直接插入排序和希尔排序)
- 三大框架Spring+Mybatis+springMVC整合
- iOS开发之同一应用设置不同图标和名称
- BASE64加密解密
- 复习总结06:Kafka
- 有头单链表的创建 ,及有头单链表逆转