来自 Google 的消息传递文档
内容脚本:
chrome.extension.sendRequest({greeting: "hello"}, function(response) { //request
console.log(response.farewell); //receive response
});
背景页面:
chrome.extension.onRequest.addListener( //listen to requests
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"}); //send response
});
您还可以在内容脚本和背景页面之间建立长期连接:
http ://code.google.com/chrome/extensions/messaging.html#connect
contentscript.js
================
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.html
===============
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."});
});
});