how to comunicate between a content script and a background page
i know this question has been asked before but i dont know hwo to 开发者_Python百科make it work.
this is the content script:
console.log("online");
chrome.extension.sendRequest({foo: "yes"}, function(response) {
console.log(response.thefoo);
});
and this is the background page:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.foo == "yes")
sendResponse({thefoo:"this is the foo"});
else
sendResponse({"it didnt work"});
});
the code that i have here, its from one of the answered questions around here with a few changes that i made, but it didnt work even when i put it exactly. you can see that answer here Chrome extension: accessing localStorage in content script
---=== 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);
you also need to have the content script defined in the manifest file
精彩评论