- Electron 教程
- Electron - 首页
- Electron - 概览
- Electron - 安装
- Electron 如何工作?
- Electron - Hello World
- Electron - 构建用户界面
- Electron - 文件处理
- Electron - 本机 Node 库
- 进程间通信 (IPC)
- Electron - 系统对话框
- Electron - 菜单
- Electron - 系统托盘
- Electron - 通知
- Electron - WebView
- Electron - 音频和视频捕获
- Electron - 定义快捷方式
- Electron - 环境变量
- Electron - 调试
- Electron - 应用打包
- Electron - 资源
- Electron 有用资源
- Electron - 快速指南
- Electron - 有用资源
- Electron - 讨论
Electron - 系统对话框
对任何一款应用程序而言,用户友好性都非常重要。因此,你不应该使用 alert() 调用创建对话框。Electron 提供了一个非常好的界面,可以完成创建对话框的任务。让我们来看看它。
Electron 提供了一个 dialog 模块,我们可以用它来显示用于打开和保存文件、发出警报等操作的本机系统对话框。
让我们直接跳到一个示例,创建一款应用程序来显示简单的文本文件。
创建一个新的 main.js 文件,并输入以下代码 -
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
const {ipcMain} = require('electron')
let win
function createWindow() {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(url.format ({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
ipcMain.on('openFile', (event, path) => {
const {dialog} = require('electron')
const fs = require('fs')
dialog.showOpenDialog(function (fileNames) {
// fileNames is an array that contains all the selected
if(fileNames === undefined) {
console.log("No file selected");
} else {
readFile(fileNames[0]);
}
});
function readFile(filepath) {
fs.readFile(filepath, 'utf-8', (err, data) => {
if(err){
alert("An error ocurred reading the file :" + err.message)
return
}
// handle the file content
event.sender.send('fileData', data)
})
}
})
app.on('ready', createWindow)
每当我们的主进程从渲染进程收到一条“openFile”消息,这段代码就会弹出一个打开对话框。这条消息将文件内容重定向回渲染进程。现在,我们必须打印该内容。
现在,创建一个新的 index.html 文件,并输入以下内容 -
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>File read using system dialogs</title>
</head>
<body>
<script type = "text/javascript">
const {ipcRenderer} = require('electron')
ipcRenderer.send('openFile', () => {
console.log("Event sent.");
})
ipcRenderer.on('fileData', (event, data) => {
document.write(data)
})
</script>
</body>
</html>
现在,每当我们运行这款应用程序,就会弹出一个本机打开对话框,如下图所示 -
一旦我们选择了一个要显示的文件,它的内容就会显示在应用程序窗口中 -
这只是 Electron 提供的四个对话框之一。它们尽管用途相同。一旦你学会了如何使用 showOpenDialog,那么你就可以使用其他任何对话框了。
具有相同功能的对话框有 -
- showSaveDialog([browserWindow, ]options[, callback])
- showMessageDialog([browserWindow, ]options[, callback])
- showErrorDialog(title, content)
广告