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

问题描述

|| 我知道以前曾问过这个问题,但我不知道如何使它起作用。 这是内容脚本:
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);
您还需要在清单文件中定义内容脚本     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...