用自定义逻辑替换customElements.define

问题描述

是否可以修改customElements.define并改用自定义函数

这是我到目前为止尝试过的方法,但是显然window.customElements是只读的,这是行不通的。

const future = ["hello-world"];

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

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

这是可能的还是我创建自己的registry并使用它的唯一选择?

解决方法

该属性仍可配置,因此您可以重新定义它。尽管对于生产应用程序来说,这似乎不是一个好主意。

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