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

Firefox插件引入onnxruntime-web触发CSP报错,求无需修改CSP的解决方法

解决Firefox插件中onnxruntime-web触发CSP错误的方案

核心问题原因

onnxruntime-web默认会使用eval()动态生成WebAssembly相关代码以优化性能,这直接违反了Firefox插件严格的Content-Security-Policy(CSP)规则,而修改CSP允许eval不仅不符合插件商店政策,还会带来安全风险。

可行解决方法

1. 配置onnxruntime-web禁用eval

在初始化推理会话前,强制库使用无eval的代码路径:

import * as ort from 'onnxruntime-web';

// 禁用eval依赖
ort.env.disableEval = true;
// 指定本地wasm文件路径(需和插件资源目录对应)
ort.env.wasm.wasmPaths = browser.runtime.getURL('assets/');

// 加载并运行模型
async function runInference() {
  const session = await ort.InferenceSession.create(
    browser.runtime.getURL('model.onnx')
  );
  // 执行推理逻辑...
}

2. 正确打包WebAssembly资源

如果使用Webpack,确保wasm文件被复制到插件资源目录而非内嵌到JS中:

  • 安装copy-webpack-plugin,然后配置Webpack:
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.wasm$/,
        type: 'asset/resource',
        generator: {
          filename: 'assets/[name][ext]'
        }
      }
    ]
  },
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: 'node_modules/onnxruntime-web/dist/*.wasm',
          to: 'assets/[name][ext]'
        }
      ]
    })
  ]
};

3. 配置插件manifest的资源访问权限

确保wasm文件和模型能被插件脚本访问,在manifest.json中添加:

{
  "manifest_version": 3,
  // ...其他配置
  "web_accessible_resources": [
    {
      "resources": ["assets/*.wasm", "model.onnx"],
      "matches": ["<all_urls>"]
    }
  ]
}

4. 避免使用依赖JIT的模型特性

如果模型包含动态算子或自定义算子,onnxruntime可能会触发eval生成代码。此时需要:

  • 将模型转换为仅使用onnxruntime-web支持的标准静态算子
  • 使用预编译的算子库替代动态生成逻辑

可能的操作失误检查

  • 未在初始化前设置ort.env.disableEval = true,导致库默认启用eval路径
  • 打包时将wasm文件内嵌到JS中,迫使库使用eval解析二进制数据
  • 使用了旧版本的onnxruntime-web,建议升级到最新稳定版以获取更好的CSP兼容性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 05:02:36