问题
I've written a Firefox extension which appends a menuitem onto the context menu and now i want to hide the item unless context of the click is on text.
For some reason the oncontextmenu event is never triggered ('context opened' is not shown on screen).
I've tried changing the to but still no alert being fired, anyone got an idea what i might be doing wrong here? thanks!
<?xml version="1.0"?>
<overlay xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script>
function contextClicked(){
alert('context opened')
var saveToFileItem = document.getElementById("saveToFile");
}
</script>
<menupopup id="contentAreaContextMenu" oncontextmenu="contextClicked();">
<script type="application/javascript" src="chrome://ffext/content/overlay.js"/>
<menuitem id="saveToFile" label="Save to File" oncommand="ffext.run();"/>
</menupopup>
</overlay>
回答1:
Don't do it like this - with onfoo
event properties there can be only one event handler. If you succeed you will likely override the default context menu handler defined by Firefox. You should be using addEventListener instead which allows adding multiple event listeners for the same event. And of course, you are using the wrong event. The contextmenu
event fires on the element that the user clicks on, not on the context menu. XUL processes this event by opening the context menu, contentAreaContextMenu
in this case. The context menu then gets its own events - namely popupshowing
and popupshown
. Context menu initialization code usually attaches to the popupshowing
event.
So you should put code similar to this into your overlay.js
file:
// Do not try to do anything before the window loads
window.addEventListener("load", function()
{
function contextClicked(event)
{
alert('context opened')
var saveToFileItem = document.getElementById("saveToFile");
}
// Add contextClicked as event listener to the context menu
var contextMenu = document.getElementById("contentAreaContextMenu");
contextMenu.addEventListener("popupshowing", contextClicked, false);
}, false);
Note that this code defines contextClicked
inside a function - this is an approach that I would generally recommend. If you define things globally you can run into a name conflict with existing Firefox code or other extensions - all of them run their code in the same namespace. By declaring your variables and functions inside an anonymous function you completely avoid this issue.
回答2:
Try to use popupshowing event.
来源:https://stackoverflow.com/questions/10677517/get-menuitem-from-context-menu-in-firefox