Search code examples
javascriptfirefoxweb-componentpolyfills

Firefox throws exception when setting `textContent` to undefined when webcomponent polyfill loaded


Our team is developing native V1 Web Components.

A fellow employee was getting an error, but only in Firefox, when running her tests for one component.

The error only happened when setting the value for textContent to undefined.


Solution

  • I created an initial test and it does not fail:

        var el = document.querySelector('#outside');
        el.textContent = 'value';
        el.textContent = undefined;
        <span id="outside"></span>

    We scratched our heads and then she pointed out that this was failing in her Web Component.

    So I loaded up the polyfill and added code to test a web component like this:

        var el = document.querySelector('#outside');
        el.textContent = 'value';
        el.textContent = undefined;
    
        // Class for `<my-el>`
        class MyEl extends HTMLElement {
          constructor() {
            super();
          }
    
          connectedCallback() {
            this.innerHTML = '<span id="inner"></span>';
    
            var el = this.querySelector('#inner');
            el.textContent = 'value';
            el.textContent = undefined;
          }
        }
    
        // Define our web component
        customElements.define('my-el', MyEl);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.0.20/webcomponents-lite.js"></script>
    <span id="outside"></span>
    <my-el></my-el>

    To my surprise the error occurred, not within the Web Component, but on the code that set the .textContent into the outer element.

    So the existing polyfill for Web Components throws an error if you try to set textContent to undefined.

    So protect your code by something like this:

    el.textContent = newValue || '';