如何在 chrome 扩展的选项页面和背景页面之间进行通信

2024-03-18

我面临一个问题。通过消息传递,我将 DOM 数据从内容脚本传输到后台页面。我想知道的是如何在选项页面和后台页面之间建立通信通道。应用程序编程接口chrome.extension.getBackgroundPage()没有用。传统的消息传递也不是通过sendRequest and addlistener在职的 。如何将此数据从后台页面传输到选项页面?有人可以提供一个经过测试的片段来解释吗?


这就是我一直在尝试的。 在我的 contentscript.js 中

    <script>
    var selected_Text ="";
    window.addEventListener("dblclick",function(event){

    selected_Text = String(window.getSelection());
    chrome.extension.sendRequest({greeting: "maprender",name:selected_Text},     function(response) {
        alert("reached here")
        console.log(response.farewell);
        });

//i am to then load options.html on DOM like this 
var Div = document.createElement("iframe");
Div.setAttribute('src', chrome.extension.getURL('options.html'));
Div.setAttribute("style","width:130px;height:80px;position:absolute;left:10px;");
Div.setAttribute("id","xyz");
document.body.appendChild(Div);
</script>

我像这样检索选定的文本作为 background.html

<script>
var Addr_details={
place:null
};
chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {

    if (request.greeting == "maprender")
     {
        alert("reached here sendin resp"+request.name);
        Addr_details.place = request.name;
        sendResponse({farewell: "goodbye"});

     }
    else
      sendResponse({}); // snub them.
  });
</script>

现在要在选项页面 options.html 访问此文本的值,我尝试了 2 种方法 一种是像这样使用 chrome.extension.getBackgroundPage() :

<script>
function init(){
var bkg = chrome.extension.getBackgroundPage();
alert("the selected text is "+bkg.Addr_details.place);
}
</script>

init 是 options.html 的 onload 。这没有给我值。事实上它只是在 chrome.extension.backgroundPage 初始化时终止。

我尝试的另一种方法是从 contentscript.js 创建一个类似的请求(就像 contentscript.js 中已经存在的请求),并使用不同的问候语,并在 options.html 中添加一个侦听器。这似乎在接收方也不起作用(选项页面)因为我在请求后在内容脚本中收到回调。我肯定做错了什么,不是吗?请帮忙。


第二种方法行不通是有道理的。 Options.html 并非始终“活动”,仅当选项页面打开时才“活动”。因此,它无法侦听来自内容脚本的请求。 这正是“背景”的用途。

至于第一种方法(使用getBackgroundPage()),我自己没有使用过这个方法,但它似乎只带回后台页面的DOM,因此无法访问后台js中的变量。

最好的办法应该是从选项页面向后台页面发送请求,询问该值,例如:

内容脚本:

chrome.extension.sendRequest({greeting: "retrieveAddr"}, function(response) {
  // do something with response.addr...
});

背景页:

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    switch (request.greeting) {
    case "maprender"):
      alert("reached here sendin resp"+request.name);
      Addr_details.place = request.name;
      sendResponse({farewell: "goodbye"});
      break;
    case "retrieveAddr":
      sendResponse({addr: Addr_details});   

    default:
      sendResponse({}); // snub them.
  });
});

另一个更简单但更黑客的解决方案是使用本地存储 https://developer.mozilla.org/en/DOM/Storage在选项和背景页面之间传递信息,因为它们共享相同的页面。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 chrome 扩展的选项页面和背景页面之间进行通信 的相关文章

随机推荐