【问题标题】:Can't import tensorflow.js in chrome extension无法在 chrome 扩展中导入 tensorflow.js
【发布时间】:2019-06-16 12:00:45
【问题描述】:

我正在开发一个 chrome 扩展,我在其中使用我训练有素的 keras 模型。为此,我需要导入一个库tensorflow.js。我该怎么做?

我尝试通过两种方式在我的项目中导入tensorflow.js

1) 在background.js import * as tf from '@tensorflow/tfjs';

2) 我下载了tf.min.js 并尝试将其添加到我的manifest.json

manifest.json

{
  "manifest_version": 2,
  "name": "my_project",
  "version": "0.1",

  "background": {
        "scripts": ["background.js", "tf.min.js"]
  },
  "content_scripts": [
      {
        "matches": [
          "<all_urls>"
        ],
        "js": ["jquery-3.1.1.min.js","content.js"]
      }
   ]
}

在第一种情况下,错误是“意外的令牌 *”;

在第二种情况下,错误是“Uncaught (in promise) ReferenceError: tf is not defined”。

我做错了什么?

【问题讨论】:

    标签: javascript tensorflow google-chrome-extension tensorflow.js


    【解决方案1】:

    我下载了tf.min.js并尝试将其添加到我的manifest.json

    尝试将tf.min.js 放在首位,如下所示:

    {
      "background": {
        "scripts": ["tf.min.js", "background.js"]
      }
    }
    

    脚本按照您指定的顺序加载,如果您希望能够在 background.js 中使用来自 tf.min.js 的内容,则必须先加载 tf.min.js

    【讨论】:

    • 感谢您的回答。不幸的是,我收到了这个错误:tf.min.js:2 Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not a allowed source of script in the following Content Security Policy directive:"script-src' self' blob:文件系统:chrome-extension-resource:“。在 eval () 在 tf.min.js:2 在 tf.min.js:2 在 Py (tf.min.js:2) 在 tf.min.js:2 在 tf.min.js:2在 tf.min.js:2
    • 原来你可能无法在 Chrome 扩展中使用 Tensorflow,因为它使用了eval。您可以阅读更多关于此herehere 的信息。我建议您导入未缩小的 tf.js 以找出该错误的确切来源。
    • 谢谢。我读过我可以让 CSP 放松,例如允许使用以下策略进行评估:"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'", 正如我所见,它有效。
    猜你喜欢
    • 2022-06-18
    • 2015-01-09
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    相关资源
    最近更新 更多