Skip to content
Advertisement

document.getElementById(“myFile”).value gets undefined using electron

I have a very basic html file (using electron);

JavaScript

and an event listener named render.js;

JavaScript

But when I click submit, document.getElementById("myFile").value returns undefined

how can I pull that value?

Advertisement

Answer

This is an interesting issue that confronts many people using Electron. One could either use (via Electron) the native OS dialog.showOpenDialog([browserWindow, ]options) dialog or the html <input type=”file”> tag.

To circumvent the need to manage the is prefixed with C:fakepath issue, it is often better to use the native approach. After all, that is what Electron is best at.

Let me show you how to quickly set up a html button that when clicked, will open the native file selector dialog, and when a path is selected, return the path to the render thread for display.

In the below code, we will be using a preload.js script configured to communicate (using IPC) between the main thread and render thread(s). Context Isolation will describe this in more detail.

First off, let’s code the main.js file which will include the creation of the native file dialog.

main.js (main thread)

JavaScript

Now, let’s create the index.html file, which for the sake of simplicity, also includes the Javascript within the <script> tags.

NB: Instead of deferring your script in the <head>, you can include it just before the closing <html> tag. Placing it here effectively performs the same thing as defer in the <head> <script> tag.

index.html (render thread)

JavaScript

Finally, let’s add the preload.js script to allow the main thread and render thread(s) to safely communicate with each other.

Note: This is where we define our whitelisted channel names.

preload.js (main thread)

JavaScript

Hopefully, the above outlines how simple it can be to use (via Electron) the native dialog boxes. The benefit being they have OS specific functionality and feel.

Advertisement