这个自主自定义元素可以在 content.js(扩展 JavaScript 上下文)和顶级 JavaScript 上下文中工作:
window.customElements.get('custom-element') || customElements.define('custom-element', class extends HTMLElement {
constructor() {
super();
console.log('custom-element constructed');
}
connectedCallback(){
console.log('custom-element connected');
}
});
let ce = document.createElement('div')
ce.innerHTML = `<custom-element name="my-element">`
document.body.appendChild(ce)
但是这个自定义的内置元素在扩展 JavaScript 上下文中不起作用,尽管它可以在顶级 JavaScript 上下文中工作。
window.customElements.get('custom-builtin-element') || customElements.define('custom-builtin-element', class extends HTMLInputElement {
constructor() {
super();
console.log('custom-builtin-element constructed');
}
connectedCallback(){
console.log('custom-builtin-element connected');
}
}, {extends: 'input'});
let cbie = document.createElement('div')
cbie.innerHTML = `<input is='custom-builtin-element' type="radio">`
document.body.appendChild(cbie)
这是manifest.json中的相关部分:
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"webcomponents-sd-ce.js",
"content.js"
]
}
]
webcomponents-sd-ce.js
是根据这个答案添加的。我也尝试过webcomponents-bundle.js
。
我的 Chrome 是最新的 根据这个答案:
Version 119.0.6045.123
。
(如何)我可以在 Chrome 扩展的 content.js 中使用自定义的内置元素吗?
如有任何建议,我们将不胜感激。预先感谢。
主要关注是命名空间冲突:
实际上是不可能的
如果扩展先行,页面将会中断。如果页面出现 首先,扩展会损坏。
由我们扩展开发人员决定
有些开发人员很棒。其他人不一定知道 某些代码的后果,这是我们的工作(平台 开发人员)尽可能减轻这种情况。
就像我说的,无论是否取决于开发人员,我们已经看到它发生了, 用户向网站所有者抱怨网站无法运行,网站 业主调查了它,找到了扩展,并最终 - 责怪我们。 也许我们会责怪延期,但是,哇,这一切都需要很长时间吗? 时间。
安全问题
我不这么认为,无非是 DOM 操作。 JS代码保留 沙盒化。
只是一次尝试和真正的走动(感谢这个回购:ungap/custom-elements):
下载此 min.js 文件到您的项目中并将其包含在您的 content_scripts 中。
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"webcomponents-sd-ce.js",
"content.js",
"min.js"
]
}
]
但正如评论所说,最佳实践是完全避免在 content.js 中使用自定义元素。