
- 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)
廣告