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

方法的细节与上述的连接事件一致

相关推荐