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

Firefox WebExtension注入外部JavaScript模块报错如何解决?

问题原因

Firefox的WebExtension安全机制明确限制:内容脚本上下文内创建的type="module"的脚本标签,仅允许加载moz-extension://协议的扩展内部资源,该限制与跨域权限无关,因此你添加目标域名权限无法解决该报错。

解决方案

方案1:使用本地脚本(推荐)

将远程脚本下载到扩展本地目录内,通过扩展内部路径加载,兼容性最好:

  1. 将some_script.js下载后放到扩展的资源目录(例如./scripts/目录下)
  2. 修改内容脚本代码:
let s = document.createElement("script");
s.setAttribute("async", "");
s.setAttribute("type", "module");
// 调用runtime.getURL获取扩展内部资源的可访问路径
s.setAttribute("src", browser.runtime.getURL("scripts/some_script.js"));
s.setAttribute("crossorigin", "anonymous")
document.body.appendChild(s)
  1. 在manifest.json中配置该脚本为可公开访问资源:
  • Manifest V2 配置:
{
  "web_accessible_resources": ["scripts/some_script.js"]
}
  • Manifest V3 配置:
{
  "web_accessible_resources": [
    {
      "resources": ["scripts/some_script.js"],
      "matches": ["<all_urls>"] // 可替换为你实际要注入的站点匹配规则
    }
  ]
}

方案2:拉取远程脚本内容注入(适用于必须使用远程脚本的场景)

通过扩展后台脚本拉取远程脚本内容,再以文本形式注入到页面,避开模块源限制:

  1. 确保manifest.json中已添加*://gamergirlandco.github.io/*权限,同时配置好后台脚本
  2. 内容脚本代码修改为:
(async () => {
  // 向后台发送消息请求拉取脚本内容
  const scriptContent = await browser.runtime.sendMessage({
    type: "fetchRemoteScript",
    url: "https://gamergirlandco.github.io/some_script.js"
  });
  const s = document.createElement("script");
  s.type = "module";
  // 直接将脚本内容写入标签
  s.textContent = scriptContent;
  document.body.appendChild(s);
})();
  1. 后台脚本添加对应消息监听:
browser.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type === "fetchRemoteScript") {
    fetch(msg.url)
      .then(res => res.text())
      .then(sendResponse);
    // 异步返回结果需要返回true告知浏览器等待响应
    return true;
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 01:03:03