繁体   English   中英

如何使用 electron 中的文件对话框?

[英]How do I use the filedialog in electron?

我是 electron 的新手,我正在尝试打开一个文件对话框,让用户 select 使用以下代码访问特定文件:

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

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

但是,当我尝试此操作时,控制台中出现错误消息:

未捕获的类型错误:无法读取未定义的属性“showSaveDialog”。

有谁知道我做错了什么?

编辑:我现在正在使用这段代码,如下所示:

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

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

在我使用以下代码调用的名为 settings.js 的文件中:

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

我使用以下代码导入脚本:

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

我试过有和没有遥控器。 我仍然得到同样的错误

如果您在main进程中使用它,这应该可以工作,如果您想从renderer进程中使用它:

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

此外,最好在脚本中定义event-handler 这是一个功能示例:

<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);
  }
}

我刚刚使用这些代码解决了它。 第一个问题是我需要启用 remoteModule enableRemoteModule: true,然后我需要使用以下代码等待 DOM 加载:

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

感谢 Majed Badawi 的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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