Custom XUL Elements with XBL

Add-ons using the techniques described in this document are considered a legacy technology in Firefox. Don't use these techniques to develop new add-ons. Use WebExtensions instead. If you maintain an add-on which uses the techniques described here, consider migrating it to use WebExtensions.

From Firefox 53 onwards, no new legacy add-ons will be accepted on addons.mozilla.org (AMO).

From Firefox 57 onwards, WebExtensions will be the only supported extension type, and Firefox will not load other types.

Even before Firefox 57, changes coming up in the Firefox platform will break many legacy extensions. These changes include multiprocess Firefox (e10s), sandboxing, and multiple content processes. Legacy extensions that are affected by these changes should migrate to WebExtensions if they can. See the "Compatibility Milestones" document for more.

A wiki page containing resources, migration paths, office hours, and more, is available to help developers transition to the new technologies.

XML Binding Language (XBL, sometimes also called Extensible Bindings Language) is a language for describing bindings that can be attached to elements in other documents. The element that the binding is attached to, called the bound element, acquires the new behavior specified by the binding.

Taken from the XBL page.

This somewhat cryptic explanation describes a very simple concept: with XBL you can create your own custom elements. XBL is heavily used in XUL, but in theory it could be applied to any XML language. XBL was submitted to the W3C for standardization, but for now it's used in XUL almost exclusively.

With XBL you can define new elements and define their properties, attributes, methods and event handlers. Many complex elements such as tabs, buttons and input controls are implemented using XBL and simpler XUL elements. As explained earlier, XUL is really just boxes, text and images.

We'll look into XBL using a modified version of the Hello World extension. Download the Hello World XBL project, build it and test it for a while. You should see a new item in the Hello World menu, that opens a Binding Test window where you can add "Persons" to a list.

XBL Basics

In order to create an XBL binding you'll need 2 files: the XBL file and a CSS file that binds an element name to your XBL declaration. If you look into the content directory, you'll see both files:

  • person.xml - this is the main binding file. It holds all the code necessary to control the new element we created. We'll look into the code throughout the rest of this section. For now, just notice the opening part of the binding element: <binding id="person">.
  • bindings.css - this is the file that associates the element name to the XBL file. It associates the xshelloperson element name to the binding defined in the XBL file. Since you can have more than one binding per file, the "#person" part points to the id of the one we want. This CSS file is located in the content because it's not something we would normally want to be replaced by a skin, and it's not really defining style; it defines content behavior instead.
If you use bindings on toolbar elements, remember to include the CSS file in the customize dialog, using the style directive in the chrome.manifest file.

With those 2 files properly defined, we can now use the new element. If you look at file bindingDialog.xul, you'll see that the CSS stylesheet is included, which means that the xshelloperson tag can now be used just like any XUL tag. In this case we're adding the "Persons" dynamically, so you'll have to look into the JS file to see how xshelloperson elements are created and added to the DOM just like any other.

addPerson : function(aEvent) {
  // ...
  let person = document.createElement("xshelloperson");
  // ...
  person.setAttribute("name", name);
  person.setAttribute("greeting", greeting);
  // ...
  personList.appendChild(person);
  // ...
},

This is where the advantage of XBL is obvious: we only need to create a single node and set some attributes. We didn't need to create a whole XUL structure that would require around 7 nodes every time a "Person" is created. XBL provides the encapsulation we needed to manage these nodes as a unit.

As a bonus, you should look into the usage of nsIFilePicker to open a "Open File" dialog in a way that looks native for all systems.

Now let's look into the XBL file, person.xml.

<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">

The bindings element is the root of the document, and it's a container for binding elements. Notice how the default namespace for the document is XBL, and the XUL namespace is defined as "xul". You'll need to keep this in mind when defining the content of the binding, because weird things can happen if you don't add "xul:" to your content nodes.

<binding id="person">

In general, you should only have one binding per file. Bindings tend to require many lines of code, and having more than one ends up making gigantic, unbrowsable files. On the other hand, if your bindings are small and have a strong relationship with each other, it makes sense to keep them together. As for the CSS file, it's usually good to have a single file declaring all bindings in your extension.

Content

Under the content tag you define the XUL content that will be displayed for your element.

<content>
  <xul:hbox>
    <xul:image class="xulshoolhello-person-image" xbl:inherits="src=image" />
    <xul:vbox flex="1">
      <xul:label xbl:inherits="value=name" />
      <xul:description xbl:inherits="value=greeting" />
    </xul:vbox>
    <xul:vbox>
      <xul:button label="&xulshoolhello.remove.label;"
        accesskey="&xulshoolhello.remove.accesskey;"
        oncommand="document.getBindingParent(this).remove(event);" />
    </xul:vbox>
  </xul:hbox>
</content>

Our element is very simple, displaying an image, a couple of text lines and a button. Here are a couple of important things to notice:

  • The "xul:" namespace must be used for all XUL tags you have in your content.
  • The xbl:inherits attribute lets your inner XUL use the attributes that are set on the node. So, if you have this: <xshelloperson name="Pete" greeting="Good morning" image="" />, then those attribute values are "inherited" to the content nodes that have this special attribute. The value attribute of the xul:label element would be "Pete".
  • The oncommand attribute of the button has some code you've probably never seen before: document.getBindingParent(this). This code gets the DOM object that corresponds to the xshelloperson tag, allowing you access to its methods and properties. In this case we're calling the remove method, which we will discuss later on.

If you need to create a container element, or any other element that has child nodes, you can use the XBL children tag in your content to indicate the place where the child nodes will be inserted. The includes attribute gives you a little more flexibility with children, but it's rarely needed.

One important thing to take into account is that you shouldn't use the id attribute in any content nodes. These nodes are part of the XUL DOM just like any other, and having an id attribute is bound to cause problems, given that you could have more than instance of your element in the same document and then multiple inner items with the same id. In order to work around this problem, the anonid attribute is used instead:

 <xul:label anonid="xulshoolhello-name-label" xbl:inherits="value=name" />

And then, in order to get a reference to the node from the JS code in your binding, we use the getAnonymousElementByAttribute DOM method:

let nameLabel =
  document.getAnonymousElementByAttribute(
    this, "anonid", "xulshoolhello-name-label");

Implementation

The implementation section defines most of the scripting side of your element. Here you can define methods and properties, as well as a constructor and a destructor for your element. JavaScript code is enclosed in CDATA sections to prevent JS and XML syntax conflicts.

Properties and Fields

The field and property tags allow you to handle element variables and access them from outside of the element.

A field holds a value that can be changed, except when the readonly attribute is set. It's very similar to a JS object variable, and we generally use a field for private variables inside of the element.

<field name="fieldName">defaultValue</field>

From inside your binding methods, you can access fields with:

this.fieldName

You can also access them from outside of the element, if you have a reference to it:

elementRef.fieldName
Just like with JS objects, all fields are publicly accessible, and we use a "_" to indicate a field is "private". 

A property is a little more robust. It is defined using a getter and setter method, allowing read-only and write-only properties, as well as more complex behavior. There are two properties defined in our binding, which are just meant for easier access to the two text attributes in the element. We use the shorthand version of the property tag:

<property name="name" onget="return this.getAttribute('name');"
  onset="this.setAttribute('name', val);" />

There's a less compact version of the property tag that should be used if the getter or setter code involves more than one line of code:

<property name="name">
  <getter><![CDATA[
    return this.getAttribute('name');
  ]]></getter>
  <setter><![CDATA[
    this.setAttribute('name', val);
  ]]></setter>
</property>

Properties can be accessed just the same as fields, and they're the ones we prefer for public members.

When you add a node to a XUL document using an XBL binding, all normal DOM operations can be performed on it. You can move it around, delete it or clone it. But there is one thing you need to know about moving or cloning your node: all internal state in the node will be lost. This means that all your properties and fields will be reset. If you want some value to be preserved after such DOM operations, you must set it as an attribute and not an internal value.

Methods

Our "Person" binding has a single method that removes the item from the list:

<method name="remove">
  <parameter name="aEvent" />
  <body><![CDATA[
    this.parentNode.removeChild(this);
  ]]></body>
</method>

As you can see, it's very easy to define a method and the parameters it takes. You can also have a return value using the return keyword, just like on regular JS code. The method uses the parent node to remove the Person node. Simple enough.

You can do almost anything from XBL code, including using XPCOM components, JS Code Modules and available chrome scripts. The main setback is that you can't have script tags defined in a binding, so you depend on the scripts that have been included in the XUL files that use the binding. Also unlike scripts, you can include stylesheets using the stylesheet XBL element. DTD and properties files can be handled just like in regular XUL.

There are two conflicting patterns that you should always keep in mind: encapsulation and separation of presentation and logic. Encapsulation mandates that you try to keep your XBL free of outside dependencies. That is, you shouldn't assume that script X will be included somewhere, because not including it will cause the binding to fail. This suggests that you should keep everything inside your binding. On the other hand, a binding is really just a presentation module. Most XUL elements have basic presentation logic, and any other functionality is processed elsewhere. Plus, XBL files are significantly harder to manage than regular JS files. We prefer to err on the side of simplicity and keep the XBL as simple as possible. If that means having outside dependencies, so be it. But you can still keep some separation and versatility by using custom events to communicate to the outside world. This way you reduce your dependency on specific scripts, and your tag behaves more like the rest.

Just like fields and properties, methods are easy to invoke if you have a reference to the object that corresponds to the node.

We have experienced problems when calling methods and setting properties on XBL nodes right after they are created and inserted to the document. This is likely due to some asynchronous operation related to node insertion. If you need to perform an operation to a node right after insertion, we recommend using a timeout to delay the operation (a timeout set to 0 works well).

Handlers

The handlers and handler XBL elements are used to define event handlers for the element. We have a "click" handler that displays the greeting when the "Person" element is clicked:

<handler phase="bubbling" event="click"><![CDATA[
  window.alert(this.greeting);
]]></handler>

Handlers are not necessary all that often, since in most cases you'll need the events to only apply to a part of the binding, not the whole thing. In those cases you just add regular event attributes to the nodes inside the content tag.

Note that with handlers a convenience arises in the fact that "this" refers to the XBL element, and so internal components can be accessed using "this.".

Inheritance

Inheritance is one of the most powerful features of XBL. It allows you to create bindings that extend existing bindings, allowing lots of code reuse and subtle behavior modifications. All you need is to use the extends attribute of the binding element:

<binding id="manager"
  extends="chrome://xulschoolhello/content/person.xml#person">

This gives you an exact copy of the "Person" binding that you can override as you please.

You could, for instance, just add a content tag with significantly different XUL content, and leave the implementation alone. You do need to be careful about keeping all anonid attributes consistent, and even some DOM structure if the code does node traversal. Sadly, you can't override only some part of the content. If you want to override it, you have to override all of it.

A more common inheritance use case is when you want to change the behavior of some methods and properties. You can leave the content alone by not including the content tag, and then just add the methods and properties you wish to override. All you need to do is match the names of the originals. All methods and properties that are not overriden will maintain their original behavior.

With inheritance you could take the richlistbox element and modify it to make a rich item tree, or create a switch button that changes state everytime it's clicked. And all with very little additional code. Keep it in mind when creating your custom elements because it can save you lots of time.

Replacing Existing XUL Elements

As seen in the beginning of this section, the actual binding process is determined by a simple CSS rule that associates the tag name with the binding. This means that you can change the binding for pretty much any element in Firefox by just adding a CSS rule! This is very powerful: it allows you to change almost any aspect of the interface of any XUL window. In conjuntion with inheritance, it's even easy to do. You can enrich the UI of a Firefox window by extending and replacing elements, which is what the Console² extension does in order to improve the Error Console window.

Replacing elements should always be a last resort solution, specially if it is done on the main browser window. It's very easy to break the UI of the application or other extensions if you do this the wrong way, so be very careful about it. If you only need to change some specific instances of an element, use very specific CSS rules.

You can use the -moz-binding property with any CSS selector.

This tutorial was kindly donated to Mozilla by Appcoast.

Document Tags and Contributors

 Contributors to this page: wbamberg, Allasso, teoli, Jorge.villalobos
 Last updated by: wbamberg,