本文介绍了如何在内容脚本和背景页面之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题以前曾被问过,但我不知道hwo是否能够正常工作。

这是内容脚本:

  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 does not work});
});

我在这里得到的代码,它来自这里的一个回答问题,我做了,但即使当我把它完全没有工作。
您可以在这里看到

解决方案

--- === background.html === ---

  / * 
*处理通过chrome.extension.sendRequest()发送的数据。
* @param请求在请求中发送的对象数据。
* @param sender对象请求的来源。
* @param callbackFunction功能请求完成时调用的方法。
* /

函数onRequest(request,sender,callbackFunction){
//您在此处的动作
};
$ b $ *
*添加请求侦听器
* /

chrome.extension.onRequest.addListener(onRequest);



== === contentScript.js === ---

 函数callbackFunction(response){
//处理响应
}

chrome.extension。 sendRequest({'action':'your action'},callbackFunction);

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


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

解决方案

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

这篇关于如何在内容脚本和背景页面之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 15:12