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

JavaScript宠物刽子手游戏扩展图片无法显示问题求助

浏览器扩展宠物刽子手游戏图片无法加载的解决方案

核心问题分析

浏览器扩展对资源文件的访问有严格的路径限制,直接使用相对路径(如images/Kit1.png)无法正确加载资源,必须通过扩展API获取合法路径,同时需要在配置文件中声明资源可访问性。

分步解决步骤

1. 确认文件结构正确性

确保你的扩展文件结构符合以下规范(文件名、大小写完全匹配):

你的扩展目录/
├── manifest.json
├── popup.html (或你的游戏页面文件)
├── script.js (你的JS代码文件)
└── images/
    ├── Kit1.png
    ├── Kit2.png
    ├── Kit3.png
    ├── Kit4.png
    ├── Kit5.png
    ├── Kit6.png
    └── gameover.png

2. 修改JS代码中的图片路径获取逻辑

替换代码中直接写相对路径的部分,使用chrome.runtime.getURL()(适配Chrome/Edge等Chromium浏览器)或browser.runtime.getURL()(适配Firefox)获取资源的绝对URL:

修改updateKitGraphic函数

function updateKitGraphic() {
  const KitContainer = document.querySelector('.Kit');
  // 生成合法的资源URL
  const imageUrl = chrome.runtime.getURL(`images/Kit${imageCount}.png`);
  KitContainer.innerHTML = `<img src="${imageUrl}" alt="Kit ${imageCount}">`;
  imageCount++;
}

修改checkWinOrLose函数中的游戏结束图片部分

function checkWinOrLose() {
  if (guessedLetters.join('') === wordToGuess) {
    const messageContainer = document.querySelector('.message');
    messageContainer.innerText = 'You win!';
    const letterButtons = document.querySelectorAll('.letters button');
    letterButtons.forEach(button => {
      button.disabled = true;
      button.removeEventListener('click', handleGuess);
    });
  } else if (wrongGuesses >= maxWrongGuesses) {
    const messageContainer = document.querySelector('.message');
    messageContainer.innerText = `You lose! The word was "${wordToGuess}".`;
    const KitContainer = document.querySelector('.Kit');
    // 同样使用runtime API获取路径
    const gameOverUrl = chrome.runtime.getURL("images/gameover.png");
    KitContainer.innerHTML = `<img src="${gameOverUrl}" alt="gameover">`;
    const letterButtons = document.querySelectorAll('.letters button');
    letterButtons.forEach(button => {
      button.disabled = true;
      button.removeEventListener('click', handleGuess);
    });
  }
}

3. 在manifest.json中声明可访问资源

浏览器默认阻止外部页面(包括扩展自身的页面)访问扩展资源,必须在配置文件中显式声明:

如果你使用Manifest V3

{
  "manifest_version": 3,
  // 其他配置项...
  "web_accessible_resources": [
    {
      "resources": ["images/*.png"],
      "matches": ["<all_urls>"]
    }
  ]
}

如果你使用Manifest V2

{
  "manifest_version": 2,
  // 其他配置项...
  "web_accessible_resources": [
    "images/*.png"
  ]
}

4. 验证与调试

  • 重新加载扩展:在浏览器扩展管理页面点击「重新加载」,确保所有修改生效
  • 检查控制台:右键扩展弹窗选择「检查」,打开开发者工具控制台,查看是否有404错误,确认路径是否正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 06:48:07