使用Stencil+Chrome扩展注入Web Component遇TrustedType错误求助
解决Stencil组件注入Chrome扩展内容脚本时的TrustedType错误
问题背景
通过Chrome扩展的内容脚本注入Stencil构建的Web Components到bard.google.com等启用Trusted Types的网站时,出现以下错误:
Unhandled Promise rejection: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment. ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML
核心原因是Stencil内部使用innerHTML操作DOM,但这类网站强制要求使用TrustedHTML赋值。已尝试两种方案无效:
- 手动实现
window.trustedTypes.createPolicy但无效果 - 尝试使用废弃的
stencil/webpack插件,不兼容Webpack 5
可行解决方案
方案1:配置Stencil原生支持Trusted Types
Stencil v2.16.0及以上版本内置Trusted Types支持,在stencil.config.ts中添加如下配置,让Stencil自动用Trusted Types处理HTML:
import { Config } from '@stencil/core'; export const config: Config = { // 保留原有配置 outputTargets: [ { type: 'dist', esmLoaderPath: '../loader', }, // 其他输出目标 ], // 新增Trusted Types配置 trustedTypes: { enabled: true, policyName: 'stencil-components-policy' } };
重新构建组件后,Stencil会自动创建合规的Trusted Types策略,所有innerHTML操作都会使用TrustedHTML对象。
方案2:在内容脚本中提前注册全局Trusted Types策略
若无法升级Stencil版本,需在注入Stencil脚本之前,在内容脚本中注册允许Stencil输出HTML的策略:
// 内容脚本优先执行此代码 if (window.trustedTypes) { window.trustedTypes.createPolicy('stencil-components-policy', { createHTML: (html) => { // 仅在完全信任Stencil生成的HTML时直接返回,也可添加针对性校验逻辑 return html; } }); }
注意:必须保证该策略在Stencil脚本加载前执行,否则Stencil初始化时会因找不到对应策略报错。
方案3:用Shadow DOM隔离组件渲染
将Stencil组件挂载到Shadow DOM中,Shadow DOM内部的innerHTML操作不受主文档的Trusted Types限制:
// 内容脚本中注入组件的代码 const container = document.createElement('div'); document.body.appendChild(container); // 创建Shadow DOM const shadowRoot = container.attachShadow({ mode: 'open' }); // 注入Stencil脚本后,在Shadow Root内渲染组件 const component = document.createElement('your-stencil-component'); shadowRoot.appendChild(component);
这种方法彻底隔离组件与主文档的安全策略,从根源避免Trusted Types冲突。
关键注意事项
- 若Chrome扩展的
manifest.json有内容安全策略声明,需允许自定义Trusted Types策略:{ "content_security_policy": { "extension_pages": "trusted-types stencil-components-policy; ...其他CSP规则" } } - 优先升级Stencil到最新稳定版,新版本对Trusted Types的支持更完善。
内容的提问来源于stack exchange,提问作者Nadav
相关产品推荐
相关产品推荐

