我正在将扩展从 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() 相互通信和 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()
获得的 tabId (即 tabs[0].id
)将 JavaScript 代码注入(inject)页面(DOM )并与其 DOM 交互。
关于javascript - 如何在 Firefox WebExtensions 中从后台与侧边栏脚本进行通信? (或相反亦然),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45123553/