how to comunicate between a content script and a background page

核能气质少年 提交于 2019-12-11 15:17:37

问题


i know this question has been asked before but i dont know hwo to 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


回答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);

you also need to have the content script defined in the manifest file



来源:https://stackoverflow.com/questions/6126984/how-to-comunicate-between-a-content-script-and-a-background-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!