Search code examples
javascriptweb-componentcustom-element

Replace customElements.define with custom logic


Is it possible to modify customElements.define and use a custom function instead?

This is what I have tried so far, but obviously this does not work because window.customElements is read only.

const future = ["hello-world"];

let customElementsRegistry = window.customElements;
const registry = {};
registry.define = function(name, constructor, options) {
  if (future.includes(name)) {    
    customElementsRegistry.define(name, constructor, options);
  }  
}
window.customElements = registry;

window.customElements.define("hello-world", HelloWorld);

Is this possible or is my only option to create my own registry and just use that one?


Solution

  • The property is still configurable so you can redefine it. Though this doesn't look like a great idea for production app.

    const future = ["hello-world"];
    
    let customElementsRegistry = window.customElements;
    const registry = {};
    registry.define = function(name, constructor, options) {
      console.log('hijacked')
      if (future.includes(name)) {
        customElementsRegistry.define(name, constructor, options);
      }
    }
    Object.defineProperty(window, "customElements", {
      get() {
        return registry
      }
    })
    
    window.customElements.define("hello-world", class HelloWorld extends HTMLElement {
      constructor() {
        super()
        this.innerHTML = "Hello World"
      }
    });
    <hello-world>Test</hello-world>