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/

欢迎补充指正!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值