如何在 Firefox WebExtensions 中从后台到侧边栏脚本进行通信? (或相反亦然)

How to communicate from a background to a sidebar script in Firefox WebExtensions? (or vice versa)

我正在将我的扩展程序从 SDK 迁移到 WebExtensions,但我找不到后台脚本和边栏之间的通信方式。这个想法是在用户单击上下文菜单时传递用户突出显示的文本和一些额外信息。我需要在 "selected-text" 输入中复制此选择,但我无法从脚本中操作边栏的 DOM...: (

browser.contextMenus.create({
  id: "save-highlighted-data",
  title: browser.i18n.getMessage("save-data"),
  contexts: ["all"],
  onclick: function(info,tab){ 

    //I got the highlighted data
    console.log("Selected text: " + info.selectionText);

    browser.sidebarAction.setPanel({ 
      panel: browser.extension.getURL("/sidebar/annotation.html")   
    }).then(function(){ 

      //In this context, "this" = the chrome window. But I can not change the document
      //  of the sidebar
      //console.log("window", this.document.querySelector("#selected-text"));
    }); 
  },
  command: "_execute_sidebar_action" //This toggles the sidebar 
});

有什么想法吗?我检查了 GitHub 存储库中的侧边栏示例,但它们只是打开了一个侧边栏,没有更多的交流,侧边栏切换操作 ("_execute_sidebar_action")

扩展的背景、内容、侧边栏等脚本可以使用 runtime.sendMessage() and runtime.onMessage.addListener()

相互通信

据我所知,侧边栏和内容 DOM 目前没有任何直接联系。

您可以使用 tabs.query() 获取 活动选项卡(可见选项卡)或任何其他选项卡

function logTabs(tabs) {
  for (let tab of tabs) {
    // tab.url requires the `tabs` permission
    console.log(tab.url);
  }
}

function onError(error) {
  console.log(`Error: ${error}`);
}

var querying = browser.tabs.query({currentWindow: true, active: true});
querying.then(logTabs, onError);

chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
  // tabs[0] is the active tab
});

然后您可以使用 tabs.executeScript() 和从 tabs.query()(即 tabs[0].id)获得的 tabId 来注入 JavaScript代码进入页面 (DOM) 并与其 DOM.

交互