如何解决如何在内容脚本和背景页面之间进行通信
|| 我知道以前曾问过这个问题,但我不知道如何使它起作用。 这是内容脚本: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浏览器扩展程序:在内容脚本中访问localStorage
解决方法
--- === 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);
您还需要在清单文件中定义内容脚本