我正在将我的扩展从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"
)所具有的更多的通信。
发布于 2017-07-18 05:59:04
扩展的背景、内容、侧边栏等脚本可以使用runtime.sendMessage()和runtime.onMessage.addListener()相互通信
AFAIK,目前在侧栏和内容DOM之间没有任何直接的联系。
您可以使用tabs.query()获取Active Tab (它是可视选项卡)或任何其他选项卡。
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交互。
https://stackoverflow.com/questions/45123553
复制相似问题