转自:http://jingyan.baidu.com/article/414eccf616e2c56b431f0a97.html
工具/原料
-
chrome浏览器
-
文本编辑器
概述
-
前面几篇文章我们介绍了browser action 、background pages、content scripts。
他们是在不同的上下文中运行的,不能彼此直接访问,有什么办法在他们之间传递数据或消息吗?答案是:消息传递(Message Passing).下面是官方文档的截图:
-
消息分为三种,一次性消息、长效消息、扩展间消息,就是文档中所说的, one-time requests, long-lived connections, cross-extension messages
-
一次性消息(one-time requests)
从content script发送给background:
chrome.runtime.sendMessage({cmd: "mycmd"}, function(response) { console.log(response); });
从background向content script发送消息:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {cmd: "mycmd"}, function(response) { console.log(response); }); });
接收方代码:
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
if (request.cmd== "mycmd")
sendResponse( "ok");
});
-
长效消息(long-lived connections)是现在消息的收发双方建立通道,然后通过这个通道收发消息。
连接主动方:
var port = chrome.runtime.connect({name: "con1"}); port.postMessage({cmd: "mycmd"}); port.onMessage.addListener(function(msg) {
if (msg.recmd== remycmd")
port.postMessage({cmd: "mycmd2"});
else if (msg.recmd== "remycmd2")
port.postMessage({cmd: "mycmd3"});
});
连接被动方:
chrome.runtime.onConnect.addListener(function(port) { console.assert(port.name == "con1"); port.onMessage.addListener(function(msg) {
if (msg.cmd== "mycmd")
port.postMessage({recmd: "remycmd"});
else if (msg.cmd == "mycmd2")
port.postMessage({recmd: "remycmd2"});
else if (msg.cmd== "mycmd3")
port.postMessage({recmd: "remycmd3"});
});
});
-
扩展间消息(cross-extension messages)是在不同的扩展之间收发消息。
下面是官方文档的代码示例:
END
一次性消息的例子
-
我们修改下前面几节的代码,演示一下one-time requests的机制。
基本思路是:
cs1.js获取到新闻列表后发送给background,background将其保存到变量中
popup每次弹出时向background获取其保存的列表,然后显示到弹出窗口中。
-
cs1.js中发送新闻列表的代码:
var newsArray=[];
for(var i=0;i<len;i++){
newsArray.push($(alist[i]).attr('title'));
}
chrome.extension.sendMessage({cmd: "setNewsArr",'arr':newsArray},function(response) {
});
-
background.js中处理消息的代码:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if(request.cmd=='setNewsArr'){
console.log(request.arr)
g_newsArr=request.arr;
}else if(request.cmd=='getNewsArr'){
sendResponse({'arr':g_newsArr});
}
})
-
popup.js中,获取新闻列表的代码:
chrome.extension.sendMessage({cmd: "getNewsArr"},function(response) {
if(response.arr){
var len=response.arr.length;
for(var i=0;i<len;i++){
$('body').append("<br>"+response.arr[i]+'<br>');
}
}
});
-
重新加载扩展,打开csdn首页,几秒钟后点击扩展图标。
END