用自定义逻辑替换 customElements.define

Replace customElements.define with custom logic

是否可以修改 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, constructor, 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, 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>