• 注册
当前位置:1313e > 默认分类 >正文

Electron之dialog

dialog, 这里译为对话框

运行环境

  • Electron version: v1.6.12
  • Operating system: CentOS Linux release 7.3.1611 (Core)

概要

对话框可以打开, 保存文件, 弹出警告等.
Electron中的对话框有两种, 一种运行在主进程上, 另一种运行在渲染进程上.

一个可以选择多个文件和目录的对话框:

// main.js
const { dialog } = require('electron');
console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']
}));

实际发现, 不加参数openDirectory时, 是可以同时多选文件和目录的,
但按官网的写法, 只能多选目录, 文件不能选, 这应该是一个bug.

我已经提了issue, 希望能有所帮助.


2017-08-13
改正, 在issue中有人回答了这个问题:

https://electron.atom.io/docs/api/dialog/#methods
Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector, so if you set properties to [‘openFile’, ‘openDirectory’] on these platforms, a directory selector will be shown.

也就是说, 在windows和linux环境下, 文件打开对话框不能同时设置[‘openFile’, ‘openDirectory’], 如果你同时设置了, 只会使用openDirectory这个选项.


上面的那种对话框是在主进程中打开的, 如果想要在渲染进程中打开对话框, 需要调用remote模块中的:

// renderer.js
const { dialog } = electron.remote;
console.log(dialog);

对话框方法

dialog.showOpenDialog([browserWindow, ]options[, callback])

打开一个文件操作对话框, 可以保存, 选择文件.
下面是点击按钮, 选择文件, 读取文件内容到页面上的例子:

<button id="selectFile">选择文件button>
<div id="fileContent">div>
// renderer.js
let electron = require('electron');
let fs = require('fs');const { ipcRenderer } = electron;
const { dialog } = electron.remote;document.getElementById('selectFile').addEventListener('click', function(e) {// 打开选择文件对话框,非模态dialog.showOpenDialog(null, {// 选择文件, 隐藏文件也显示出来properties: ['openFile', 'showHiddenFiles'],// 后缀为html, js, json, md其中之一filters: [{name: 'Text', extensions: ['html', 'js', 'json', 'md'] }]}, function(filenames) {// filenames是一个数组, 每一项为选择的文件的绝对路径let firstFile = filenames[0],fileContentEle = document.getElementById('fileContent');if (firstFile) {fs.readFile(firstFile, 'utf8', function(err, data) {if (err) {// 如果读取错误, 弹出错误提示窗口dialog.showErrorBox('error', `read ${firstFile} error`);return;}fileContentEle.innerText = data;});} else {fileContentEle.innerText = 'no file selected';}});
},false);

在上述例子中, 我引入了nodejs中的fs模块, 来读取文件的内容.
这也就是说, node中的其他模块可以随意使用, 非常自由.
这里也可以通过FileReader来读取文件, 不过是为了演示如何使用node中的模块而已.

另外, 不选择文件直接取消时, 无法触发fileContentEle.innerText = 'no file selected';句代码, 不知道是哪里的问题.

另外的几个打开对话窗口的方法, 使用方法类似, 具体参数可以看官网的描述.

参考:
https://electron.atom.io/docs/api/dialog/

欢迎补充指正!

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录