Add example for menus.getTargetElement API (#369)

This commit is contained in:
Rob Wu
2018-09-05 20:02:53 +02:00
committed by wbamberg
parent 7d587095ac
commit 4c3d87e214
7 changed files with 304 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
"use strict";
// The browser.menus.getTargetElement API allows extensions to identify the
// clicked element that matches a menus.onClicked or menus.onShown event, as of
// Firefox 63.
//
// This polyfill script approximates the behavior, by returning the target of
// the most recently observed contextmenu event in this document.
//
// Limitations:
// - Cannot return the menu target before this script has run.
// In contrast, the real menus.getTargetElement API will return the element
// even if the extension did not run any scripts at the time of the click.
//
// - Does not offer the guarantee that the element matches the menus.onClicked
// or menus.onShown event.
// In contrast, the real menus.getTargetElement API only returns an element
// if the given first parameter matches the info.targetElementId integer from
// the menus.onClicked or menus.onShown events.
if (!browser.menus || !browser.menus.getTargetElement) {
var menuTarget = null;
let cleanupIfNeeded = () => {
if (menuTarget && !document.contains(menuTarget)) menuTarget = null;
};
document.addEventListener("contextmenu", (event) => {
menuTarget = event.target;
}, true);
document.addEventListener("visibilitychange", cleanupIfNeeded, true);
browser.menus = browser.menus || {};
browser.menus.getTargetElement = () => {
cleanupIfNeeded();
return menuTarget;
};
true; // Used by popup.js, as variable didUsePolyfill.
}