iandis / isolated_worker

An isolated worker for Flutter (Isolate) and Web (Web Worker). Behaves almost the same as the compute function, except it is not a one-off worker.
MIT License
42 stars 11 forks source link

Import modules into fetch_function.js file #12

Closed jonnyjohnson1 closed 2 years ago

jonnyjohnson1 commented 2 years ago

I have the scripts working the way you have shown. Thank you.

I'm trying to take it a step further in using js packages, specifically node-jsencrypt. This is probably a JS question, and I am just unfamiliar with the JS specifics.

How can I load the JS Encrypt package to use with this?

In my dart file to trigger the JSIsolated Worked:

bool _areScriptsImported = false;
  static const List<String> _jsScripts = <String>[
    'fetch_function.js',
  ];

Future<String> jsIsolateDecrypt(String message) async {
    if (!_areScriptsImported) {
      await JsIsolatedWorker().importScripts(_jsScripts);
      _areScriptsImported = true;
    }
    String decrypted = await JsIsolatedWorker().run(
      functionName: 'getDecrypt',
      arguments: message,
    ) as String;
    return decrypted;
  }

Inside the fetch_function.js file:

const JSEncrypt = require('node-jsencrypt')

function getDecrypt(encrypted) {
  var crypt = new JSEncrypt();
  crypt.setPrivateKey(privateKey);
  return crypt.decrypt(encrypted);
}

I get this error:

Error: ReferenceError: Cannot access 'JSEncrypt' before initialization

Any ideas? Thank you.

iandis commented 2 years ago

Hi @jonnyjohnson1, from what I recently saw, the node-jsencrypt depends on the DOM which is not supported by Web Workers. So you might need to use the jsencrypt instead. And for the importing module part, I think you need to import the module using JsIsolatedWorker.importScripts (or just use the importScripts inside of your js file) instead of using require. I actually wrote an example for that, but didn't publish it on README. Here's the link

jonnyjohnson1 commented 2 years ago

@iandis Thank you. That was what was needed.

Here was what I did to import the jsencrypt library.

self.window = self
self.importScripts('https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/3.2.1/jsencrypt.min.js');

Then this function could be executed pulling JSEncrypt from the package.

function getDecrypt(encrypted) {
  var crypt = new JSEncrypt();
  crypt.setPrivateKey(privateKey);
  return crypt.decrypt(encrypted);
}
iandis commented 2 years ago

@jonnyjohnson1 Cool! I'm glad it works! Though I'd suggest you to just download the jsencrypt.min.js and put it in your web directory, so that way every time your app runs it doesn't need to download the file. Anyways, should you have another question, feel free to tag me here. Otherwise, please kindly close this issue if the solution is enough for you. Thanks!