关于在 bg.html、popup.html 和 contentscript.js 之间发送消息

2023-12-01

在我的扩展中,当一个名为mybuttonl in popup.html是 单击,它会发送一条消息"getvar" to contentscript.js,这又发送一条消息"I want var1" to background.html获取一个名为的对象var1。 (一个名为mybutton2是同样设置的,除了它得到var2单击时的对象)。

我应该如何实施这个?

更重要的是,我有点困惑chrome.extension.onRequest.addListener and chrome.extension.sendRequest方法。有人可以解释一下吗?


onRequest.addListener 和 sendRequest 是 Chrome 扩展消息传递的一部分。位于此处http://developer.chrome.com/extensions/messaging.html

基本上,您使用“onRequest.addListener”监听某人通过触发“sendRequest”发送的请求。

在你的情况下,你放了一个“onRequest.addListener” 在您的内容脚本中侦听来自弹出窗口的请求(使用发送请求)。从您的内容脚本中,您可以将响应返回到弹出窗口以处理正在发生的情况。在弹出窗口中,您可以使用直接访问后台页面chrome.extension.getBackgroundPage().

如果您希望内容脚本也与后台页面通信(这不是必需的,因为您使事情变得更加复杂),您可以将“onRequest.addListener”添加到后台页面,该页面仅侦听来自内容脚本的请求。要做到这一点,消息传递完美地解释了它。 “sender.tab”如果为 true,则为内容脚本。

下面的示例(未经测试)显示了我对消息传递的含义。请记住,尽量让事情变得简单,而不是复杂。

Example

弹出窗口.html

chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendRequest(tab.id, {method: "fromPopup", tabid: tab.id}, function(response) {
    console.log(response.data);
  });
});

ContentScript.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.method == "fromPopup") {
    // Send JSON data back to Popup.
    sendResponse({data: "from Content Script to Popup"});

    // Send JSON data to background page.
    chrome.extension.sendRequest({method: "fromContentScript"}, function(response) {
      console.log(response.data);
    });
  } else {
    sendResponse({}); // snub them.
  }
});

背景页.html

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  // From content script.
  if (sender.tab) {
    if (request.method == "fromContentScript")
      sendResponse({data: "Response from Background Page"});
    else
      sendResponse({}); // snub them.
  }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于在 bg.html、popup.html 和 contentscript.js 之间发送消息 的相关文章

随机推荐