Javascript Chrome 中的 Tensorflow 由于 'unsafe-eval' 扩展不工作

Javascript Tensorflow in Chrome Extension not working due to 'unsafe-eval'

我正在尝试将我的 Chrome 扩展更新为 Manifest v3。我使用 JSTensorflow 模型并弹出此错误:

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'".

我知道 Manifest v3 不允许 'unsafe-eval',那么我该如何解决这个问题?

我的manifest.json:

{
    "name": "Recipick DEVELOPMENT",
    "description": "Pick the recipe from a website",
    "version": "1.0.0",
    "manifest_version": 3,
    "background": {
        "service_worker": "background.js",
        "type": "module"
    },
    "action": {
        "default_title": "Recipick",
        "default_icon": "/images/icon_1.png"
    },
    "permissions": [
        "activeTab",
        "clipboardWrite",
        "sessions",
        "scripting",
        "storage",
        "tabs"
    ],
    "host_permissions": [ "*://*/*" ],
    "content_security_policy": {
        "extension_pages": "script-src 'self'; object-src 'self'"
    },
    "web_accessible_resources":  [{
        "resources": [ "*.gif" ],
        "matches": [ "*://*/*" ] 
    }]
} 

感谢您的帮助!

Here 我们了解到 chrome 使用名为 Content Security Policy.

的东西禁止任何外部资源或任何包含 eval() 的脚本

我也是运行一个与你想法相同的项目,只是运行遇到了同样的问题。它还在该页面上提到了一些解决方法,包括:

  1. 使用'templating library'(符合规则的库)

  2. 访问远程内容(将请求发送到在那里进行处理的外部服务器)

据我所知,没有 tensorflow.js 符合,因此 #2 可能是这里唯一的答案。

我刚知道怎么做。

如果您在沙盒环境中使用它们,您可以使用 'unsafe-eval' 和其他不允许的操作。正如https://developer.chrome.com/docs/extensions/mv3/manifest/sandbox/中所说:

A sandboxed page will not have access to extension APIs, or direct access to non-sandboxed pages (it may communicate with them via postMessage()).

A sandboxed page is not subject to the Content Security Policy (CSP) used by the rest of the extension (it has its own separate CSP value). This means that, for example, it can use inline script and eval.

我创建了一个名为 sandbox.html 的 HTML 页面,并将其插入到我想作为 iframe 处理的页面中,其中嵌入了脚本。然后接收要在那里处理的数据并通过 window.postMessage() 返回给 Content/Background 脚本(在本例中为 window.parent.postMessage(),因为它是一个 iframe)。

这是此实现的示例:https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/apps/samples/sandbox

此页面也可能有用:https://developer.chrome.com/docs/extensions/mv3/sandboxingEval/