• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Add-ons
  1. MDN
  2. Mozilla
  3. Add-ons
  4. Overlay extensions
  5. XUL School Tutorial
  6. Custom XUL Elements with XBL

Custom XUL Elements with XBL

In This Article
  1. XBL Basics
  2. Content
  3. Implementation
    1. Properties and Fields
    2. Methods
  4. Handlers
  5. Inheritance
  6. Replacing Existing XUL Elements

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.

« PreviousNext »

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.

« PreviousNext »

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, Jul 4, 2016, 1:45:48 PM
See also
  1. WebExtensions
  2. Getting started
    1. What are WebExtensions?
    2. Your first WebExtension
    3. Your second WebExtension
    4. Anatomy of a WebExtension
    5. Example WebExtensions
  3. How to
    1. Intercept HTTP requests
    2. Modify a web page
    3. Add a button to the toolbar
    4. Implement a settings page
  4. Concepts
    1. Using the JavaScript APIs
    2. User interface components
    3. Content scripts
    4. Match patterns
    5. Internationalization
    6. Content Security Policy
    7. Native messaging
  5. Porting
    1. Porting a Google Chrome extension
    2. Porting a legacy Firefox add-on
    3. Embedded WebExtensions
    4. Comparison with the Add-on SDK
    5. Comparison with XUL/XPCOM extensions
    6. Chrome incompatibilities
  6. Firefox workflow
    1. Temporary Installation in Firefox
    2. Debugging
    3. Getting started with web-ext
    4. web-ext command reference
    5. WebExtensions and the Add-on ID
    6. Publishing your WebExtension
  7. JavaScript APIs
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browsingData
    6. commands
    7. contextMenus
    8. contextualIdentities
    9. cookies
    10. downloads
    11. events
    12. extension
    13. extensionTypes
    14. history
    15. i18n
    16. identity
    17. idle
    18. management
    19. notifications
    20. omnibox
    21. pageAction
    22. runtime
    23. sessions
    24. sidebarAction
    25. storage
    26. tabs
    27. topSites
    28. webNavigation
    29. webRequest
    30. windows
  8. Manifest keys
    1. applications
    2. author
    3. background
    4. browser_action
    5. chrome_url_overrides
    6. commands
    7. content_scripts
    8. content_security_policy
    9. default_locale
    10. description
    11. developer
    12. homepage_url
    13. icons
    14. manifest_version
    15. name
    16. omnibox
    17. options_ui
    18. page_action
    19. permissions
    20. short_name
    21. sidebar_action
    22. version
    23. web_accessible_resources
  9. Add-on SDK
  10. Getting started
    1. Installation
    2. Getting started
    3. Troubleshooting
  11. High-Level APIs
    1. addon-page
    2. base64
    3. clipboard
    4. context-menu
    5. hotkeys
    6. indexed-db
    7. l10n
    8. notifications
    9. page-mod
    10. page-worker
    11. panel
    12. passwords
    13. private-browsing
    14. querystring
    15. request
    16. selection
    17. self
    18. simple-prefs
    19. simple-storage
    20. system
    21. tabs
    22. timers
    23. ui
    24. url
    25. webextension
    26. widget
    27. windows
  12. Low-Level APIs
    1. /loader
    2. chrome
    3. console/plain-text
    4. console/traceback
    5. content/content
    6. content/loader
    7. content/mod
    8. content/symbiont
    9. content/worker
    10. core/heritage
    11. core/namespace
    12. core/promise
    13. dev/panel
    14. event/core
    15. event/target
    16. frame/hidden-frame
    17. frame/utils
    18. fs/path
    19. io/byte-streams
    20. io/file
    21. io/text-streams
    22. lang/functional
    23. lang/type
    24. loader/cuddlefish
    25. loader/sandbox
    26. net/url
    27. net/xhr
    28. places/bookmarks
    29. places/favicon
    30. places/history
    31. platform/xpcom
    32. preferences/event-target
    33. preferences/service
    34. remote/child
    35. remote/parent
    36. stylesheet/style
    37. stylesheet/utils
    38. system/child_process
    39. system/environment
    40. system/events
    41. system/runtime
    42. system/unload
    43. system/xul-app
    44. tabs/utils
    45. test/assert
    46. test/harness
    47. test/httpd
    48. test/runner
    49. test/utils
    50. ui/button/action
    51. ui/button/toggle
    52. ui/frame
    53. ui/id
    54. ui/sidebar
    55. ui/toolbar
    56. util/array
    57. util/collection
    58. util/deprecate
    59. util/list
    60. util/match-pattern
    61. util/object
    62. util/uuid
    63. window/utils
  13. Firefox for Android
  14. Getting started
    1. Walkthrough
    2. Debugging
    3. Code snippets
  15. APIs
    1. Accounts.jsm
    2. BrowserApp
    3. HelperApps.jsm
    4. Home.jsm
    5. HomeProvider.jsm
    6. JavaAddonManager.jsm
    7. NativeWindow
    8. Notifications.jsm
    9. PageActions.jsm
    10. Prompt.jsm
    11. RuntimePermissions.jsm
    12. Snackbars.jsm
    13. Sound.jsm
    14. Tab
  16. Legacy
  17. Restartless extensions
    1. Overview
  18. Overlay extensions
    1. Overview
  19. Themes
  20. Lightweight themes
    1. Overview
  21. Complete themes
    1. Overview
  22. Publishing add-ons
  23. Guides
    1. Signing and distribution overview
    2. Submit an add-on
    3. Review policies
    4. Developer agreement
    5. Featured add-ons
    6. Contact addons.mozilla.org
  24. Community and support
  25. Channels
    1. Add-ons blog
    2. Add-on forums
    3. Stack Overflow
    4. Development newsgroup
    5. IRC Channel