How do I convert an extension which uses XBL to use a custom element?

127 Views Asked by At

I have an overlay Thunderbird extension. It uses XBL to alter the Help menu in Thunderbird’s menu bar, where it replaces the original menu items with a single "Hello, World!" menu item.

Help menu in Thunderbird’s menu bar, where the original menu items have been replaced with a single "Hello, World!" menu item.

As XBL is on its way out, I would like to update the extension to use a custom element.

Currently the binding is attached like so:

bindings.css

menu#helpMenu {
  -moz-binding: url("./test.xml#helpMenu");
}

test.xml

<?xml version="1.0"?>

<bindings
  xmlns="http://www.mozilla.org/xbl"
  xmlns:xbl="http://www.mozilla.org/xbl"
  xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
  <!-- Original helpMenu implementation found in omi.ja/chrome/messenger/content/messenger/mailWindowOverlay.xul -->
  <binding id="helpMenu">
    <content>
      <xul:menupopup>
        <xul:menuitem
          label="Hello, World!"
          oncommand="alert('Hello, World!')"
        />
      </xul:menupopup>

      <children />
    </content>
  </binding>
</bindings>

How can I convert this code to use a custom element?

I have searched online, but all of the material I have found (example) demonstrates how to create a custom element and insert it into a parent.

I don't want to do this. I want to create a custom element and then use it to replace an element that already exists in Thunderbird's interface (in this case a <menupopup>).

Can anyone help me out?

The full code for the extension is available on GitHub.

1

There are 1 best solutions below

0
On

I solved my own issue by hooking into the <menupopup> element in the XUL file and nesting my custom element inside of that. I then used JavaScript to remove the menu elements I didn't need.

I'm not sure if this is the best solution, but it does what I need. I'd still be interested in hearing if there is a better way, though.

test.xul

<?xml version="1.0"?>
<overlay xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
  <script>
    const popup = document.getElementById('menu_HelpPopup');
    const separators = popup.querySelectorAll('menuseparator');
    const items = popup.querySelectorAll('menuitem:not(#test)');
    [...items, ...separators].forEach((item) => { item.parentNode.removeChild(item) });
  </script>
  <script src="test.js"></script>

  <menupopup id="menu_HelpPopup">
    <help-menu />
  </menupopup>
</overlay>

test.js

"use strict";

// This is loaded into all XUL windows.
// Wrap in a block to prevent leaking to window scope.
{
  class MozHelpMenu extends MozXULElement {
    connectedCallback() {
      this.appendChild(MozXULElement.parseXULToFragment(`
        <menuitem id="test" label="Hello, World!" oncommand="alert('Hello, World!')" />
      `));
    }
  }

  customElements.define('help-menu', MozHelpMenu);
}