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



我正在将我的扩展从SDK迁移到WebExtensions,但我找不到后台脚本和侧边栏之间的通信方式。这个想法是在用户单击上下文菜单时传递用户突出显示的文本和一些额外信息。我需要在"所选文本"输入中复制此选择,但我无法从脚本中操作侧边栏的 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()和runtime.onMessage.addListener()相互通信

AFAIK,目前侧边栏和内容 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()获得的tabId一起使用(即tabs[0].id)将JavaScript代码注入页面(DOM)并与其DOM交互。

最新更新