Daveman
Daveman

Reputation: 1096

How to get custom elements working in Firefox?

I have this basic custom element example. It is working in Chrome, however not in Firefox. Is there a way to get it working in Firefox (without polymer but maybe some kind of polyfill)?

I also enabled the dom.webcomponents.enabled flag without any success.


Update:

Since this is solved, I created a repository, with the complete code: https://github.com/peplow/webcomponent-example/


Custom element html file:

<template id="template">
  <button id="button">Hallo</button>
  <style media="screen">
    button{
      color:red;
    }
  </style>
</template>

<script>
    var localDoc = document.currentScript.ownerDocument;
    class toggleButton extends HTMLElement{

      constructor(){
        super();
        this.shadow = this.attachShadow({mode: 'open'});
        var template = localDoc.querySelector('#template');
        this.shadow.appendChild(template.content.cloneNode(true));

        this.shadow.querySelector('button').onclick = function(){
          alert("Hello World");
        }
      }

      static get observedAttributes() {return ['name']; }

      attributeChangedCallback(attr, oldValue, newValue) {
        if (attr == 'name') {
          this.shadow.querySelector('#button').innerHTML = newValue;
        }
      }

    }

    customElements.define('x-toggle', toggleButton);
</script>

File where it is used:

<!DOCTYPE html>
<html>
  <head>
    <link rel="import" href="element.html">
    <meta charset="utf-8">
  </head>
  <body>
    <x-toggle name="Hello World"></x-toggle>
  </body>
</html>

Upvotes: 8

Views: 7054

Answers (2)

Mendy
Mendy

Reputation: 8682

As of June 2018, Firefox support for Custom Elements can be enabled with the following steps

  1. Type in the search bar about:config.
  2. search for dom.webcomponents.shadowdom.enabled click to enable.
  3. serch for dom.webcomponents.customelements.enabled click to enable.

Hope this helps someone out there.

UPDATE: Now, since Firefox 63, Custom Elements are supported in Firefox by default.

Upvotes: 13

JohnRiv
JohnRiv

Reputation: 306

Firefox has not yet shipped Custom Elements v1, which is the latest standard and is what specifies customElements.define() as the way to define an element (as opposed to v0 which used document.registerElement() and is what is available with the dom.webcomponents.enabled flag in Firefox).

Chrome is currently the only browser that supports Custom Elements v1 natively, but all other major browsers are supportive of it.

Firefox has an open bug for Custom Elements v1 support.

In the meantime, your best bet is to use the Custom Elements v1 Polyfill for browsers that don't support it. You can feature-detect Custom Elements v1 support with 'customElements' in window.

Upvotes: 11

Related Questions