如何解决用自定义逻辑替换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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。