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

发布于 2024-11-09 09:28:54 字数 653 浏览 1 评论 0原文

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

这是内容脚本:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无远思近则忧 2024-11-16 09:28:54

---==== 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);

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

---=== 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文