Offering a context menu for form controls

Firefox 3 changed the behavior of right-click on form controls to no longer display a context menu by default.  This article describes how an extension can override this change in a particular window, enabling context menus to work on form controls.

This article presents information based on Ehsan Akhgari's Form Control Context Menu extension, which was created specifically to demonstrate how to do this.

There is ongoing discussion about this topic; please see bug 433168 for the latest information.

Overlay the content

The first thing to do is to establish an overlay over the chrome for the window in which you want to allow context menus on form controls.

<overlay id="formcontrolcontextmenu-overlay"
  <script type="application/javascript" src="chrome://formcontrolcontextmenu/content/overlay.js"/>

Change the right-click behavior

The overlaid code is responsible for adjusting the behavior of right-clicking on form controls.

window.addEventListener("load", function() {
    let setTargetOriginal = nsContextMenu.prototype.setTarget;
    nsContextMenu.prototype.setTarget = function(aNode, aRangeParent, aRangeOffset) {
      setTargetOriginal.apply(this, arguments);
      if (this.isTargetAFormControl(aNode))
        this.shouldDisplay = true;
  }, false);

This code, which is run when the window is opened up, works by replacing the setTarget() routine for the prototype of nsContextMenu with one that forces the context menu to display if the target of the menu is a form control.

As a result, all controls in the window will support a context menu when right-clicked, since we've changed the core behavior of context menus to override their default behavior of doing nothing on form controls.

Document Tags and Contributors

 Last updated by: Sheppy,