Electron-system-dialogs

提供:Dev Guides
移動先:案内検索

Electron-システムダイアログ

すべてのアプリがユーザーフレンドリーなものであることが非常に重要です。 そのため、alert()呼び出しを使用してダイアログボックスを作成しないでください。 Electronは、ダイアログボックスを作成するタスクを達成するための非常に優れたインターフェースを提供します。 それを見てみましょう。

Electronは、ファイルを開いたり保存したりするためのネイティブシステムダイアログの表示、警告などに使用できる*ダイアログ*モジュールを提供します。

例に直接ジャンプして、簡単なテキストファイルを表示するアプリを作成しましょう。

新しい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, 'indexl'),
      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」メッセージを受信するたびに、開いているダイアログボックスをポップします。 このメッセージは、ファイルコンテンツをレンダラープロセスにリダイレクトします。 次に、コンテンツを印刷する必要があります。

ここで、次の内容で新しい indexl ファイルを作成します-

<!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が提供する4つのダイアログの1つにすぎません。 しかし、それらはすべて同様の使用法を持っています。 showOpenDialog を使用してその方法を学習したら、他のダイアログを使用できます。

同じ機能を持つダイアログは-

  • showSaveDialog([browserWindow、] options [、callback])
  • showMessageDialog([browserWindow、] options [、callback])
  • showErrorDialog(title、content)