Search code examples
javascriptjquerymenuelectron

How to show an open file native dialog with Electron?


I am trying to add functionality to my Electron app that will allow users to open a file in the app, specifically plain text files. After looking at the Electron documentation, I found this page. I added this code to my app.js file, which I linked to in my index.html.

var fs = require('fs');
var dialog = require('electron');
$openFile = $('#openBtn');
$editor = $('#editor');

$openFile.click(function(){
  dialog.showOpenDialog(function(fileNames) {
    if (fileNames === undefined) return;
    var fileName = fileNames[0];

    fs.readFile(fileName, 'utf-8', function (err, data) {
      $editor.val(data);
    });
  });
});

However, when I run this, this error shows up in the console: Uncaught TypeError: dialog.showOpenDialog is not a function I have tried using remote, but to no avail.

Has anyone know how to fix this problem? Thanks in advance


Solution

  • const {dialog} = require('electron').remote;
    
    document.querySelector('#selectBtn').addEventListener('click', function (event) {
        dialog.showOpenDialog({
            properties: ['openFile', 'multiSelections']
        }, function (files) {
            if (files !== undefined) {
                // handle files
            }
        });
    });