How can I open new BrowserWindow in Web Worker?


#1

Hello everybody!
Is there any way open new Browser Window in Web Worker?
I use this guide about multithreading in electron and I am trying to use this examples in my project, but nothing works. Here is a part of my code:

//main_func.js:

const session = require('electron');
const BrowserWindow = remote.BrowserWindow;

function check () {
    var worker = new Worker('js/thread_func.js');
    worker.postMessage('Message');

    worker.onmessage = function(e)
    {
        console.log('Got message from Worker: ' + e.data);
        console.log(e.data);
    }
}

// thread_func.js
onmessage = function(e) {
    const {BrowserWindow} = require('electron').remote

    let win = new BrowserWindow({width: 800, height: 600})
    win.on('closed', () => {
        win = null
    })

    win.loadURL('https://github.com')
}

I am not sure, that it is possible to use require keyword in such files like this. (which is used by Web Workers)

Now my error message is below:
Uncaught Error: ENOENT, worker/api/exports/electron.js not found in /Users/kirill/Desktop/TW/node_modules/electron/dist/Electron.app/Contents/Resources/electron.asar
at notFoundError (ELECTRON_ASAR.js:115)
at Object.fs.readFileSync (ELECTRON_ASAR.js:513)
at Object.Module._extensions…js (module.js:579)
at Module.load (module.js:503)
at tryModuleLoad (module.js:466)
at Function.Module._load (module.js:458)
at Module.require (module.js:513)
at require (internal/module.js:11)
at onmessage (thread_func.js:33)
ELECTRON_ASAR.js:119

Uncaught Error: ENOENT, worker/api/exports/electron.js not found in /Users/kirill/Desktop/TW/node_modules/electron/dist/Electron.app/Contents/Resources/electron.asar

So, is there any way to open new Browser Window in separated thread using Electron JS?

p.s. My main.js file:


const {app, BrowserWindow} = require('electron')
var mainWindow = null;

app.on('window-all-closed', function() {
  if (process.platform != 'darwin') {
    app.quit();
  }
});

app.on('ready', function() {
  mainWindow = new BrowserWindow({width: 800, height: 600, resizable: true, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true }});
  mainWindow.loadURL('file://' + __dirname + '/index.html');
  mainWindow.on('closed', function() {
    mainWindow = null;
  });
});

#2

I think what you need to do is from worker thread, you postmessage to mainthread to open window instead of having the code that open window in the worker thread.

so the architect should be like this:

The main.js opens first window (index.html)
at index.html, it loads main_func.js and it creates new worker (thread_func.js)
at thread_func.js, it does something as you want, then postmessage back to main_func.js to create window.
at main_func.js, it handles worker.onmessage with proper message event by your definition, to open new browser window.