neutralinojs / neutralino.js

JavaScript API for Neutralinojs
https://neutralino.js.org/docs/api/overview
MIT License
239 stars 53 forks source link

Web Workers Neu.storage not appearing in Folder #27

Open danidre14 opened 3 years ago

danidre14 commented 3 years ago

Expected Behavior

When you import Neu in the web worker and try to use Neutralino.storage.putData or Neutralino.storage.getData in the worker, it should appear in the .storage folder, just as when you call the functions in the main Window scope.

Actual Behavior

When you import Neu in the web worker and try to use Neutralino.storage.putData or Neutralino.storage.getData in the worker, it doesn't fail or error out, however, the .storage folder does not populate with the new bucket file.

Steps to Reproduce the Problem

1. Create a worker thread. var myWorker = new Worker(URL); 2. Within the worker, import Neu and call the functions in the onmessage:

importScripts("../../resources/js/neutralino.js");
self.onmessage = async function () {
  for(var i = 10; i < 18; i++) {
    console.log("uid"+i);
    await Neu.storage.putData({ bucket: "uid"+i, data: "uid"+i });
  }
}

3. Post a message to the worker from the main file:

// within button click
myWorker.postMessage("Hello world");

When run and the button pressed, the console logs uid10 all the way up to uid17 from the console.log, however, the .storage file does not have the newly created files.

Specifications

danidre14 commented 3 years ago

After extensive reviewing of the neutralinojs code (after running it in a beautifier), I realized that the functions send a fetch request to the server through the port. However, you use window.NL_PORT. It occurred to me that window is undefined in a worker.

The current hack way I did for it to work was to do:

var window = self;
importScripts("../../resources/js/neutralino.js");
self.onmessage = async function () {
 for(var i = 10; i < 18; i++) {
   console.log("uid"+i);
   await Neu.storage.putData({ bucket: "uid"+i, data: "uid"+i });
 }
}

I had to put the window as the webworker process before importing the neu script to the web worker. Thus, it will populate the properties into the window object, and then access them when making the request.

I think this is a flaw on neu's end, it should check if it is in a webworker or not, and provide some functions or not depending on whether it is or not.

I will create another issue with that feature as a request.

When you are ready, you can close this issue, since it is solved.