3

So I'm aware without react on the render thread I can do this to open a file dialog.

const {dialog} = require('electron').remote
dialog.showOpenDialog({properties: ['openFile']}))

I'm trying to use react and learn the workflows of React & Electron though. Doing the require gives me the following error.

TypeError: fs.existsSync is not a function
getElectronPath
   5 | var pathFile = path.join(__dirname, 'path.txt');
   6 | 
   7 | function getElectronPath() {
>  8 |   if (fs.existsSync(pathFile)) {
   9 |     var executablePath = fs.readFileSync(pathFile, 'utf-8');
  10 | 
  11 |     if (process.env.ELECTRON_OVERRIDE_DIST_PATH) {
View compiled
(anonymous function)
  18 |   }
  19 | }
  20 | 
> 21 | module.exports = getElectronPath();
View compiled

Unsure what I can do to make this work. Should be a pretty simple canvas drawing app, but i do need to enumerate images in folders & give file dialog capabilities to the app. Any ideas how to remedy this issue?

2
  • Have you tried to cast a event from the main thread and listen for it on the renderer thread? Commented Nov 23, 2018 at 10:20
  • I think it is failing because of the React pre-compiler not understanding what is going on. Not anything innately wrong with the code. I'll need to dispatch an even from the render thread to trigger it on the main thread in this situation unless I want to put it in a menu or something. Goal is to have a nice looking html button spawn the file dialog. Commented Nov 24, 2018 at 2:07

1 Answer 1

8

I found a solution. You can run a preload.js into a window on creation and then call the items like javascript objects.

Found this issue on the github https://github.com/electron/electron/issues/9920

  mainWindow = new BrowserWindow({
    width: 800, 
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      preload: __dirname + '/preload.js'
    }
  });

Preload.js

const { dialog } = require('electron').remote;
window.electron = {};
window.electron.dialog = dialog;

Then anything I want to load into the window I can just add to the window.electron object and call it with no issues. React pre-compiler is more the issue than anything with electron.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried your solution. But I'm still getting undefined for the dialog object. I tried using the dialog object directly under the electron module(remove the remote attribute in line 1 of ppreload.js) but it still doesn't work. Mind if you help me?
@Beast stackoverflow.com/questions/37884130/… this says the require has changed with the newer versions of Electron. Replace the require in my example with require('@electron/remote') .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.