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

Chrome扩展加载TensorFlow模型提示无本地对应模型报错如何解决?

问题原因

  • 你对TensorFlow.js的localstorage://加载协议用法理解错误:该协议仅支持读取通过tf.Model.save('localstorage://xxx')接口存储的模型,TensorFlow.js会按内部约定格式存储模型拓扑、权重元数据等完整信息,你手动将model.json序列化为字符串存入localStorage的结构和TensorFlow.js预期的结构完全不匹配,因此会抛出找不到对应模型的报错。
  • 你已经将模型文件放在扩展本地目录下,完全没必要绕localStorage存储的中间步骤,直接加载扩展内静态资源即可。

推荐解决方案(直接加载扩展本地模型)

该方案无需依赖localStorage,不会触发存储上限问题,稳定性更高。

  1. 首先在manifest.json中配置模型文件的可访问权限,示例如下:
    如果使用Manifest V3:
{
  "web_accessible_resources": [
    {
      "resources": ["model/*"],
      "matches": ["<all_urls>"]
    }
  ]
}

如果使用Manifest V2:

{
  "web_accessible_resources": ["model/*"]
}

注意将resources路径替换为你实际存放model.json和bin权重文件的目录路径。

  1. 修改加载代码,通过chrome.runtime.getURL生成扩展资源的合法访问路径:
async function load_model() {
    // 替换为你的model.json在扩展目录中的实际相对路径
    const modelJsonPath = chrome.runtime.getURL('model/model.json');
    const model = await tf.loadLayersModel(modelJsonPath);
    return model;
}

特殊场景方案(必须通过localStorage加载)

如果你的业务场景确实需要先把模型存入localStorage再加载,按如下步骤操作:

// 首次使用:先加载本地模型,再通过TensorFlow.js官方接口存入localStorage
async function initAndSaveModel() {
    const modelJsonPath = chrome.runtime.getURL('model/model.json');
    const model = await tf.loadLayersModel(modelJsonPath);
    await model.save('localstorage://model');
    return model;
}

// 后续加载时才可以使用localstorage协议读取
async function load_model() {
    const model = await tf.loadLayersModel('localstorage://model');
    return model;
}

注意:localStorage通用存储上限为5MB左右,如果你的模型大小超过该上限会导致存储失败,后续加载也会报错,大体积模型不推荐使用该方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:15:07