4

I am developing a chrome extension, where I use my trained keras model. For this I need to import a library tensorflow.js. How should I do that?

I tried to import tensorflow.js in my project by two ways:

  1. in background.js by import * as tf from '@tensorflow/tfjs';

  2. I downloaded tf.min.js and tried to add it in my 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"]
      }
   ]
}

In the first case the error was "unexpected token *";

and in the second case the error was Uncaught (in promise) ReferenceError: tf is not defined.

What did I do wrong?

greatwolf
  • 20,287
  • 13
  • 71
  • 105
my name
  • 41
  • 2

1 Answers1

4

I downloaded tf.min.js and tried to add it in my manifest.json

Try putting the tf.min.js first, like this:

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

The scripts are loaded in the order you specify them and if you want to be able to use things from tf.min.js inside of background.js, tf.min.js has to be loaded first.

Niklas Higi
  • 2,188
  • 1
  • 14
  • 30
  • Thank you for answering. Unfortunately, I got this error: tf.min.js:2 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' blob: filesystem: chrome-extension-resource:". at eval () at tf.min.js:2 at tf.min.js:2 at Py (tf.min.js:2) at tf.min.js:2 at tf.min.js:2 at tf.min.js:2 – my name Jun 16 '19 at 12:13
  • Turns out you might not be able to use Tensorflow in Chrome extensions because it uses `eval`. You can read more on this [here](https://stackoverflow.com/a/48047578/6662225) and [here](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy#eval()_and_friends). I'd recommend you to import the unminifed `tf.js` to figure out where exactly that error is coming from. – Niklas Higi Jun 16 '19 at 12:21
  • 2
    Thank you. I have read that I can make the CSP be relaxed, e.g. allowing eval using the following policy: `"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",` And as I see, it works. – my name Jun 16 '19 at 12:44