如何在内容脚本和后台页面之间进行通信

时间:2011-05-25 15:28:36

标签: google-chrome google-chrome-extension messaging

我知道之前已经问过这个问题,但我不知道hwo能让它发挥作用。

这是内容脚本:

console.log("online");
chrome.extension.sendRequest({foo: "yes"}, function(response) {
console.log(response.thefoo);
});

这是背景页面:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.foo == "yes")
  sendResponse({thefoo:"this is the foo"});
else
  sendResponse({"it didnt work"});
});

我在这里的代码,它来自这里的一个已回答的问题,我做了一些更改,但即使我完全按照它也没有用。 你可以在这里看到答案Chrome extension: accessing localStorage in content script

1 个答案:

答案 0 :(得分:1)

--- === background.html === ---

/*
 * Handles data sent via chrome.extension.sendRequest().
 * @param request Object Data sent in the request.
 * @param sender Object Origin of the request.
 * @param callbackFunction Function The method to call when the request completes.
 */

function onRequest(request, sender, callbackFunction) {
    //your actions here
};

/*
 * Add request listener
 */

 chrome.extension.onRequest.addListener(onRequest);

--- === contentScript.js === ---

function callbackFunction(response) {
    //process the response
}

chrome.extension.sendRequest({'action': 'your action'}, callbackFunction);

您还需要在清单文件中定义内容脚本