[英]How to get the right-clicked tab's URL in a Firefox add-on
我正在写一个Firefox扩展,它将菜单项添加到浏览器的选项卡上下文菜单中,以将选项卡的URL发送到Web服务。 我的菜单项有一个command
事件侦听器,该事件在选择菜单项时触发,并且工作正常。
我遇到的麻烦是根据收到的事件弄清楚右键单击了哪个选项卡。 从菜单项本身( command
事件的目标)到选项卡似乎并不容易,因为选项卡上下文菜单不是XUL领域中选项卡的子级。 我当然不能仅仅获得当前标签,因为用户可能右键单击了一个非活动标签。
我当前使用的解决方案是在每个选项卡上放置一个contextmenu
事件处理程序,该选项卡将选项卡的URL存储在全局变量中,并在command
事件处理程序中使用此全局变量。 这很好用,并且我有点同意全局变量,因为实际上不可能同时显示多个上下文菜单。
但是有更好的方法吗? 我曾想过使用一个保存URL的闭包来更新command
事件处理程序,但是这样做的缺点是需要在添加新事件处理程序之前先删除旧的事件处理程序,这只会使事情更加复杂。
我当前的代码如下所示:
var tabs = require("sdk/tabs");
var xultabs = require("sdk/tabs/utils");
var viewFor = require("sdk/view/core").viewFor;
var itemid = "my-extension-name";
var xulns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
// global variable to hold tab URL and function to set it on right-click of tab
taburl = "";
function getTabURL(e) { taburl = xultabs.getTabURL(e.target); }
tabs.on('ready', function(tab) {
// set up event listener to get tab URL when tab is right-clicked
let vtab = viewFor(tab);
vtab.addEventListener("contextmenu", getTabURL);
// add our context menu item if it's not already there
let doc = viewFor(tab.window).document;
if (!doc.getElementById(itemid)) {
let menu = doc.getElementById("tabContextMenu");
let item = doc.createElementNS(xulns, "menuseparator");
menu.appendChild(item);
item = doc.createElementNS(xulns, "menuitem");
item.setAttribute("label", "My Menu Item");
item.setAttribute("id", itemid);
item.addEventListener("command", function() { pushURL(taburl) });
menu.appendChild(item);
}
});
function pushURL(url) {
// pushes the URL to the service
}
显示上下文菜单时,您可以通过执行以下操作找出触发了弹出窗口的元素:
e.target.ownerDocument.popupNode
这可能很有用,但实际上您需要的只是ownerDocument.defaultView
我认为甚至还有保存浏览器窗口的e.view
属性。
因此,例如:
function contextMenuShowing(e) {
console.log('context menu showing', 'popupNode:', e.target.ownerDocument.popupNode);
var currentWindow = e.target.ownerDocument.defaultView; // can try var currentWindow = e.view;
if (currentWindow.gBrowser) {
var tabURL = gBrowser.selectedBrowser.currentURI;
}
}
cToolbarContextMenu.addEventListener('popupshowing', contextMenuShowing, false);
另一种方法是因为单击鼠标右键显然意味着窗口已聚焦。 因此,您可以执行以下操作:
const { getMostRecentBrowserWindow } = require('sdk/window/utils');
cToolbarContextMenu.addEventListener('popupshowing', function() {
var currentWindow = getMostRecentBrowserWindow();
if (currentWindow.gBrowser) {
var tabURL = currentWindow.gBrowser.selectedBrowser.currentURI.spec;
}
}, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.