导入“@tensorflow/tfjs”以在 Chrome 扩展中使用本地模型时出错

Error when importing '@tensorflow/tfjs' to use local model in Chrome extension

我试图在我的 chrome 扩展中使用 tensorflow 本地模型。 在 contentScript:

import * as tf from '@tensorflow/tfjs';
const MODEL_URL = './model/model.json';
const model = tf.load_model(MODEL_URL);
model.run("text");

我的manifest.json:

  "content_security_policy": {
    "extension_pages": "script-src 'self' http://localhost; object-src 'self';"
  },
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_title": "My extension",
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs", 
    "history", 
    "background", 
    "webNavigation", 
    "activeTab", 
    "storage"
  ],
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "run_at": "document_start",
      "js": [
        "contentScript.js"
      ]
    }
  ]

但是我得到了错误Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'".

我的package.json:

{
  "name": "my-extension",
  "version": "0.1.0",
  "description": "My Chrome Extension",
  "private": true,
  "scripts": {
    "watch": "webpack --mode=development --watch --config config/webpack.config.js",
    "build": "webpack --mode=production --config config/webpack.config.js"
  },
  "devDependencies": {
    "copy-webpack-plugin": "^6.4.1",
    "css-loader": "^4.3.0",
    "file-loader": "^6.2.0",
    "mini-css-extract-plugin": "^0.10.1",
    "size-plugin": "^2.0.2",
    "webpack": "^4.46.0",
    "webpack-cli": "^3.3.12",
    "webpack-merge": "^5.8.0"
  },
  "dependencies": {
    "@tensorflow/tfjs": "^3.16.0",
    "@tensorflow/tfjs-node": "^3.16.0"
  }
}

使用本地模型的正确方法应该是什么?

TL;DR -

清单版本 3 不允许使用 'unsafe-eval'。您需要将库代码捆绑在您的扩展程序中,或者使用您的扩展程序将调用的外部 API,例如 message-passing.

使用 links 稍微更冗长 -

来自official overview for manifest version 3-

A key security improvement in Manifest V3 is that extensions can't load remote code like JavaScript or Wasm files. This lets us more reliably and efficiently review the safe behavior of extensions when they're submitted to the Chrome Web Store. Specifically, all logic must be included in the extension's package.

Instead of remote code, we recommend the use of remote configuration files. See the migration guide for more about how to work with this change.

这是 link 到 migration guide section on remotely hosted code (PS - 不在这里粘贴整个内容,因为这些指南可能会更新)