RSS

Electron: Hello World について

08 8月

Electron のページで Quick Start を開くと “Hello World” のサンプルが出ています。

このサンプルは、github にもソースが置いてあり次のようになっています。

github

Quick Start の主要ファイル

  • package.json
    このプロジェクトの主要ファイルとその詳細、依存関係のリスト
  • main.js
    アプリのメインプロセスで、アプリを開始しメインウィンドウを開く。
  • index.html
    メインウィンドウの画面を定義。

package.json

{
  "name": "helloworld",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "author": "",
  "license": "ISC",
  "scripts": {
    "start": "electron ."
  }
}

main.js

// main.js

const { app, BrowserWindow } = require('electron')
const path = require('path')

// app.whenReady() の中でコールされる関数でメインウィンドウの詳細を定義している。
const createWindow = () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  mainWindow.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// この部分は Mac で実行しないなら不要。
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.
  </body>
</html>

その他のファイル

  • preload.js
    アプリが完全にロードされる前のプロセスを記述するが、後述するプロセス間通信を使う場合には改造することもある。
  • renderer.js (github サンプルでは存在)
    index.html のレンダリングプロセス中にコールされるが、このサンプルでは使わないので存在しない。index.html の <script> タグでロードする。後述するプロセス間通信を行う場合、改造する可能性がある。
  • style.css (github サンプルでは存在)
    スタイルシート。index.html の <link> タグでロードする。

独自アプリを作る際の主な改造箇所

package.json

  • name を適切なものに変更。

main.js

  • ウィンドウタイトル
  • ウィンドウサイズ
  • ウィンドウスタイル
  • イベントハンドラ

詳細は BrowseWindow 参照

index.html

  • フォームを追加するなど

イベントハンドラ

Electron のイベントの多くは app オブジェクト、BrowserWindow などで定義されており、それらについてハンドラを記述する。

イベントハンドラの例

const { app } = require('electron')
app.on('window-all-closed', () => {
  app.quit()
})

HTML のコントロールのイベントは、HTML DOM で定義されている通りであり、従来通りにイベントハンドラを定義して処理できる。

もちろん、jQuery や Vue.js のようなものも利用できる。

ローカルリソースへのアクセス

ブラウザはローカルファイルなどに直接アクセスできないが、Electron はネイティブアプリのようにローカルリソースにアクセスできるようなメカニズムを持っている。

ブラウザウィンドウは Chrome ベースなので直接、ローカルリソースにアクセスできないが、内部プロシージャコール (IPC) というメカニズムにより、ネイティブで動作する ipcMain というプロセス にローカルリソースをアクセスするのを委託する。

詳細はプロセス間通信参照

次のサンプルは Electron の「プロセス間通信」に出ているサンプルです。

main.js

const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

function createWindow () {
  const mainWindow = new BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  ipcMain.on('set-title', (event, title) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win.setTitle(title)
  })

  mainWindow.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow()
  
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

preload.js

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
    setTitle: (title) => ipcRenderer.send('set-title', title)
})

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    Title: <input id="title"/>
    <button id="btn" type="button">Set</button>
    <script src="./renderer.js"></script>
  </body>
</html>

renderer.js

const setButton = document.getElementById('btn')
const titleInput = document.getElementById('title')
setButton.addEventListener('click', () => {
    const title = titleInput.value
    window.electronAPI.setTitle(title)
});
 
コメントする

投稿者: : 2022/08/08 投稿先 Electron, JavaScript, Node.js

 

コメントを残す