Message Passing 消息传递
Simpleone-timerequests:发送一个简单的json数据从一个contentscript发送到插件的background.html文件中,反之亦然
chrome.extension.sendRequest()或chrome.tabs.sendRequest()methods
可选的一个回调函数,可以用于接收返回的内容
如:定义在contentscript文件中
chrome.extension.sendRequest({greeting: "hello"}, function(response) {
console.log(response.farewell);
}); 在background发送使用特殊一些,需要使用getSelected获取选中的tab后,然后发送请求
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
}); 接收的代码为:
chrome.extension.onRequest.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"});
else
sendResponse({}); // snub them.
});Long-livedconnections长周期连接
能够保持连接,持续的进行数据收发
从contentscript连接到background(插件)的代码
var port = chrome.extension.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
if (msg.question == "Who's there?")
port.postMessage({answer: "Madame"});
else if (msg.question == "Madame who?")
port.postMessage({answer: "Madame... Bovary");
}); 如果要从background插件处发起连接,需要稍作修改,去获取指定的id
chrome.tabs.connect(tabId,{name:"knockknock"}).
设置监听连接的监听器
chrome.extension.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function(msg) {
if (msg.joke == "Knock knock")
port.postMessage({question: "Who's there?"});
else if (msg.answer == "Madame")
port.postMessage({question: "Madame who?"});
else if (msg.answer == "Madame... Bovary")
port.postMessage({question: "I don't get it."});
});
});对应的监听断开方法Port.disconnect(),和对应的事件Port.onDisconnect
Cross-extensionmessaging跨插件消息
主要使用chrome.extension.onRequestExternalorchrome.extension.onConnectExternal
方法的细节与上述的连接事件一致
相关推荐
Mynamezhuang 2020-09-18
Ladyseven 2020-10-22
luofuIT成长记录 2020-09-22
李鴻耀 2020-08-17
yaodilu 2020-08-03
zhoujiyu 2020-06-28
89510194 2020-06-27
CaiKanXP 2020-06-13
MaureenChen 2020-06-12
Phoebe的学习天地 2020-06-07
淡风wisdon大大 2020-06-06
buttonChan 2020-06-06
xtuhcy 2020-05-20
AlisaClass 2020-05-18
赵家小少爷 2020-05-16
nicepainkiller 2020-05-05