[英]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:我是 electron 的新手,我正在尝试打开一个文件对话框,让用户 select 使用以下代码访问特定文件:
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.
未捕获的类型错误:无法读取未定义的属性“showSaveDialog”。
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:在我使用以下代码调用的名为 settings.js 的文件中:
<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:如果您在
main
进程中使用它,这应该可以工作,如果您想从renderer
进程中使用它:
const { dialog } = require('electron').remote;
Also, it's better to define the event-handler
in the script.此外,最好在脚本中定义
event-handler
。 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:第一个问题是我需要启用 remoteModule
enableRemoteModule: true,
然后我需要使用以下代码等待 DOM 加载:
window.onload=function(){
document.getElementById("dialogBtn").addEventListener("click", openFileDialog);
}
Thank you Majed Badawi for the help!感谢 Majed Badawi 的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.