简体   繁体   中英

How do I use the filedialog in electron?

I am new to electron and I am trying to open a filedialog that lets the user select a specific file using this code:

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

function openFileDialog() {
    const savePath = dialog.showSaveDialog();
    console.log(savePath)
}

However when I try this I get an error in the console saying:

Uncaught TypeError: Cannot read property 'showSaveDialog' of undefined.

Does anyone know what I am doing wrong?

EDIT : I am using this piece of code now as it was proposed below:

var remote = require("remote");
var dialog = require('dialog').remote; 

function openFileDialog() {
    const savePath = dialog.showSaveDialog(null);
    console.log(savePath)
}

inside a file named settings.js which I invoke using this code:

<input class="btn btn-dark" type="button" value="Input" onclick="openFileDialog();">

And I import the script using this code:

   <script src="./../javascript/settings.js"></script>

I have tried both with and without remote. I still get the same error

This should work if you're using it in the main process, if you want to use it from a renderer process:

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

Also, it's better to define the event-handler in the script. Here is a functional example:

<input class="btn btn-dark" type="button" value="Input" id="dialogBtn">
const { dialog } = require('electron').remote;

document.getElementById("dialogBtn").addEventListener("click", openFileDialog);

async function openFileDialog() {
  try {
    const savePath = await dialog.showSaveDialog(null);
    console.log('savePath: ', savePath);
  } catch (e) {
    console.log('Error:', e);
  }
}

I just solved it using these pieces of code. The first problem was that I needed to enable remoteModule enableRemoteModule: true, then that I needed to wait for the DOM to load using this code:

window.onload=function(){
    document.getElementById("dialogBtn").addEventListener("click", openFileDialog);
}

Thank you Majed Badawi for the help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM