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

Chrome扩展Manifest V3中chrome.runtime.getURL无法注入JS文件问题

Chrome扩展MV3迁移:资源注入文件找不到问题

问题说明

将Chrome扩展迁移至Manifest V3(MV3)后,已配置web_accessible_resources字段,但在内容脚本中通过chrome.runtime.getURL注入资源时,出现文件找不到错误:

  • GET: Chrome-extension:://"the_url/inject_script.js" net::ERR_FILE_NOT_FOUND

已按照MV3要求使用Web资源的内容根路径,以下是相关配置与代码:

Manifest.json配置

{
  "manifest_version": 3,
  "name": "Extension Prototype",
  "description": "Prototype for Canvas Extension",
  "version": "0.1.0",

  "icons": {
  },

  "web_accessible_resources": [{
    "resources": ["frontend/canvas-chrome-ext/src/scripts/inject_script.js"],
    "matches": ["<all_urls>"]
  }],

  "action": {
    "default_popup": "components/popup.html",
    "default_icon": "images/su_emblem.png"
  },
  "permissions": [
    "activeTab",
    "<all_urls>",
    "tabs",
    "scripting"
  ],

  "background": {
    "service_worker": "background.js"
  },

  "content_scripts": [{
    "matches": ["https://seattleu.instructure.com/", "*://www.google.com/", "https://canvas.instructure.com/*"],
    "js": ["scripts/Content.js"]
  }]
}

内容脚本(Content.js)

用于创建script DOM元素,注入inject_script.js以向网页添加按钮:

function injectScript(file_path, tag){
    var node = document.getElementsByTagName(tag)[0];
    var script = document.createElement("script");
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', file_path);
    node.appendChild(script);
}

injectScript(chrome.runtime.getURL("frontend/canvas-chrome-ext/src/scripts/inject_script.js"), 'body');

项目目录

项目目录

解决方案

  • 验证路径准确性:从项目目录截图确认inject_script.js相对于manifest.json的实际路径,确保配置和代码中的路径完全一致,避免拼写或层级错误。
  • 简化资源配置:使用通配符减少路径拼写出错概率,修改web_accessible_resources:
    "web_accessible_resources": [{
      "resources": ["frontend/**/*.js"],
      "matches": ["<all_urls>"]
    }]
    
  • 排查生成的URL:在内容脚本中添加日志,确认chrome.runtime.getURL返回的地址是否正确:
    const targetUrl = chrome.runtime.getURL("frontend/canvas-chrome-ext/src/scripts/inject_script.js");
    console.log("生成的资源URL:", targetUrl);
    injectScript(targetUrl, 'body');
    
  • 检查构建工具配置:如果使用Webpack、Vite等构建工具,需确保inject_script.js被正确打包到输出目录,且manifest中的路径对应打包后的文件位置,而非源码路径。
  • 确认匹配规则覆盖范围:虽然当前matches配置为<all_urls>,但需确保目标网站在内容脚本的matches列表中,避免因页面不匹配导致资源无法加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:32:17