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