You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展导入html2canvas时动态模块获取失败,求修复方案

解决Chrome扩展动态导入模块失败的TypeError错误

错误原因分析

出现Uncaught (in promise) TypeError: Failed to fetch dynamically imported module错误,核心原因是:

  • content.js使用了ES模块的import语法,但扩展配置未声明该资源为模块类型
  • 动态导入时Chrome无法正确识别文件的模块属性,导致加载失败

解决方案

1. 更新manifest.json配置

修改web_accessible_resources节点,添加type: "module"和use_dynamic_url: true,让Chrome将目标资源识别为可动态导入的ES模块:

"content_scripts": [
  {
      "matches": ["<all_urls>"],
      "js": [ "script.js" ]
  }
],
"web_accessible_resources": [
  {
    "matches": ["<all_urls>"],
    "resources": [
        "js/content.js",
        "js/html2canvas.js"
    ],
    "type": "module",
    "use_dynamic_url": true
  }
]

2. 校验文件路径与依赖

  • 确认js/content.js和js/html2canvas.js的实际文件位置与配置路径完全一致,避免拼写错误或层级错误
  • 确保html2canvas.js是可直接导入的ES模块版本,若使用npm包需先打包后放入对应目录

3. 优化content.js代码(可选)

简化重复DOM操作,提升代码可读性:

import html2canvas from './html2canvas.js';

const body = document.body;
// 创建触发按钮
const captureBtn = document.createElement('button');
captureBtn.id = 'captcha-btn';
captureBtn.textContent = 'test';
body.prepend(captureBtn);
// 创建结果展示图片
const resultImg = document.createElement('img');
resultImg.id = 'result';
body.prepend(resultImg);
// 绑定截图事件
captureBtn.addEventListener('click', () => {
  html2canvas(body).then(canvas => {
    resultImg.src = canvas.toDataURL();
  });
});

4. 重新加载扩展

修改配置后,进入Chrome扩展管理页面点击「重新加载」按钮,确保新配置生效。

内容的提问来源于stack exchange,提问作者Skyyade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 09:57:32