Electron ネイティブ機能統合

Electron が強力なのは、フロントエンドを書くだけでなく、メニュー、ダイアログ、トレイ、通知、グローバルショートカットキーなどのシステムのネイティブ機能にアクセスできるからです。

この章では、メインプロセスモジュールを介してこれらの機能を呼び出す方法を見ていきます。


メニューシステム

Electron はMenuモジュールを提供し、メニューバー、コンテキストメニュー、システムトレイメニューの作成に使用します。

アプリケーションメニュー(Menu)

アプリケーションメニューは、ウィンドウ上部(macOS)またはアプリケーションウィンドウ内に表示されるメニューバーです。

例

const { app, Menu } = require('electron')

const template = [
  {
    label: 'ファイル',
    submenu: [
      { label: '新規ファイル', accelerator: 'CmdOrCtrl+N', click: () => console.log('新規ファイル') },
      { label: '開く...', accelerator: 'CmdOrCtrl+O' },
      { type: 'separator' },
      { label: 終了, role: 'quit' }
    ]
  },
  {
    label: '編集',
    submenu: [
      { role: 'undo' },
      { role: 'redo' },
      { type: 'separator' },
      { role: 'cut' },
      { role: 'copy' },
      { role: 'paste' }
    ]
  }
]

const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)

説明:

  • label:メニュータイトル。
  • submenu:サブメニュー配列。
  • accelerator:ショートカットキー(macOS、Windows 共通の書き方CmdOrCtrl+X)。
  • role:システム定義済みの動作、例:quit、copy、paste。
  • click:クリックイベントのコールバック関数。

コンテキストメニュー(Context Menu)

右クリックメニューは通常レンダラープロセスでトリガーされます:

例

// main.js
const { ipcMain, Menu } = require('electron')

ipcMain.on('show-context-menu', (event) => {
  const menu = Menu.buildFromTemplate([
    { label: '更新', click: () => event.sender.reload() },
    { label: 'コピー', role: 'copy' },
    { label: '貼り付け', role: 'paste' }
  ])
  menu.popup()
})

例

// renderer.js
window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  window.electronAPI.showContextMenu()
})

システムトレイメニュー

システム通知領域にアイコンとメニューを表示します。

例

const { Tray, Menu, nativeImage } = require('electron')
let tray = null

function createTray() {
  const icon = nativeImage.createFromPath('icon.png')
  tray = new Tray(icon)
  const contextMenu = Menu.buildFromTemplate([
    { label: 'メインウィンドウを開く', click: () => mainWindow.show() },
    { label: 終了, click: () => app.quit() }
  ])
  tray.setToolTip('私の Electron アプリ')
  tray.setContextMenu(contextMenu)
}

メニューショートカットキー

を通じてaccelerator定義します。例:

{ label: '保存', accelerator: 'CmdOrCtrl+S', click: saveFile }
  • CmdOrCtrl:macOS/Windows に自動対応します。
  • Alt+F4:Windows ではウィンドウを閉じます。
  • Cmd+Q:macOS ではアプリを終了します。

システムダイアログ

dialogモジュールはネイティブのファイル、メッセージ、エラーなどのシステムダイアログを提供します。

ファイル/フォルダー選択
const { dialog } = require('electron')
async function openFileDialog() {
  const result = await dialog.showOpenDialog({
    title: '选择文件',
    properties: ['openFile', 'multiSelections'],
    filters: [{ name: '文本文件', extensions: ['txt', 'md'] }]
  })
  console.log(result.filePaths)
}

保存ダイアログ

async function saveFileDialog() {
  const result = await dialog.showSaveDialog({
    title: '保存文件',
    defaultPath: '新建文档.txt'
  })
  console.log(result.filePath)
}

メッセージ/エラーダイアログ

dialog.showMessageBox({
  type: 'info',
  title: '提示',
  message: '操作已完成!'
})

dialog.showErrorBox('错误', '文件保存失败,请重试。')

システムトレイ

トレイ(Tray)を使用すると、アプリがバックグラウンドで実行されている間もシステムアイコンを介して操作できます。

トレイアイコンの作成

const { Tray } = require('electron')
const path = require('path')

let tray = new Tray(path.join(__dirname, 'trayIcon.png'))

トレイメニューとツールチップ

const contextMenu = Menu.buildFromTemplate([
  { label: '显示窗口', click: () => mainWindow.show() },
  { label: '退出', click: () => app.quit() }
])
tray.setToolTip('Electron 应用运行中')
tray.setContextMenu(contextMenu)

トレイ通知

tray.displayBalloon({
  icon: path.join(__dirname, 'icon.png'),
  title: '新消息',
  content: '您有一条新通知'
})

トレイに最小化

クローズイベントを監視してウィンドウを非表示にします:

mainWindow.on('close', (event) => {
  event.preventDefault()
  mainWindow.hide()
})

通知(Notifications)

Electron のNotificationクラスはクロスプラットフォームでシステム通知を表示できます。

システム通知の送信

new Notification({
  title: '任务完成',
  body: '您的文件已下载完成'
}).show()

通知のインタラクション処理

const notif = new Notification({ title: '点击通知', body: '点击我触发事件' })
notif.on('click', () => {
  console.log('用户点击了通知')
})
notif.show()

クロスプラットフォーム互換性

  • macOS、Windows、Linux すべて対応;
  • macOS では「通知権限」を有効にする必要があります;
  • Linux では通常システムのサポートが必要ですlibnotify。

グローバルショートカットキー

を通じてglobalShortcutシステムレベルのホットキーを登録します。

グローバルショートカットキーの登録

const { globalShortcut } = require('electron')

app.whenReady().then(() => {
  globalShortcut.register('CmdOrCtrl+Shift+I', () => {
    console.log('快捷键触发:打开调试工具')
    mainWindow.webContents.openDevTools()
  })
})

ショートカットキー競合の処理

登録前に検出できます:

if (globalShortcut.isRegistered('CmdOrCtrl+Shift+I')) {
  console.log('快捷键已被占用')
}

プラットフォーム差異の処理

条件分岐を使用できます:

const shortcut = process.platform === 'darwin' ? 'Cmd+Shift+T' : 'Ctrl+Shift+T'
globalShortcut.register(shortcut, () => console.log('快捷键触发'))

まとめ

機能 モジュール 代表的な用途
メニュー Menu アプリケーションメニュー、右クリックメニュー、トレイメニュー
ダイアログ dialog ファイルを開く、ファイルを保存、ヒントやエラーを表示
トレイ Tray バックグラウンド実行、システム状態の表示
通知 Notification イベントの進行状況をユーザーに通知、システムリマインダー
グローバルショートカットキー globalShortcut システムレベルのショートカット操作を登録

Electron ネイティブ機能デモプロジェクト

プロジェクト構造

my-electron-native-demo/
├── package.json
├── main.js             # 主进程逻辑
├── preload.js          # 预加载脚本(安全通信)
└── index.html          # 主界面

package.json

注意:JSONファイルにコメントを書かないでください(EJSONPARSEエラーが発生します)

{
  "name": "my-electron-native-demo",
  "version": "1.0.0",
  "description": "Electron 原生功能演示项目",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "latest"
  }
}

依存関係をインストール:

npm install

アプリを起動:

npm start

main.js(メインプロセス)

例

const { app, BrowserWindow, Menu, Tray, dialog, Notification, globalShortcut, ipcMain } = require('electron')
const path = require('path')

let mainWindow, tray

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

  mainWindow.loadFile('index.html')

  // ページ読み込み完了後に表示
  mainWindow.once('ready-to-show', () => mainWindow.show())

  // ウィンドウのクローズを監視:トレイに最小化
  mainWindow.on('close', (event) => {
    event.preventDefault()
    mainWindow.hide()
  })
}

function createMenu() {
  const template = [
    {
      label: 'ファイル',
      submenu: [
        { label: 'ファイルを開く', click: openFile },
        { label: 'ファイルを保存', click: saveFile },
        { type: 'separator' },
        { label: 終了, click: () => app.quit() }
      ]
    },
    {
      label: 'ツール',
      submenu: [
        { label: '通知を表示', click: showNotification },
        { label: 'バージョン情報', click: showAbout }
      ]
    }
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

function createTray() {
  const icon = path.join(__dirname, 'icon.png')  // 16x16 または 32x32 のアイコンを用意してください
  tray = new Tray(icon)
  const contextMenu = Menu.buildFromTemplate([
    { label: 'ウィンドウを表示', click: () => mainWindow.show() },
    { label: 終了, click: () => app.quit() }
  ])
  tray.setToolTip('Electron ネイティブ機能デモ')
  tray.setContextMenu(contextMenu)
}

function registerShortcuts() {
  globalShortcut.register('CmdOrCtrl+Shift+I', () => {
    mainWindow.webContents.openDevTools()
  })
}

async function openFile() {
  const result = await dialog.showOpenDialog({
    properties: ['openFile'],
    filters: [{ name: 'テキストファイル', extensions: ['txt', 'md'] }]
  })
  if (!result.canceled && result.filePaths.length > 0) {
    mainWindow.webContents.send('file-opened', result.filePaths[0])
  }
}

async function saveFile() {
  const result = await dialog.showSaveDialog({
    title: 'ファイルを保存',
    defaultPath: '新規ドキュメント.txt'
  })
  if (!result.canceled) {
    dialog.showMessageBox({ type: 'info', message:`ファイルは次の場所に保存されます:${result.filePath}` })
  }
}

function showNotification() {
  const notif = new Notification({
    title: 'Electron 通知',
    body: 'これはシステム通知です!'
  })
  notif.on('click', () => {
    dialog.showMessageBox({ message: '通知をクリックしました!' })
  })
  notif.show()
}

function showAbout() {
  dialog.showMessageBox({
    type: 'info',
    title: 'バージョン情報',
    message: 'Electron ネイティブ機能デモプロジェクト\nバージョン:1.0.0'
  })
}

// レンダラープロセスからの呼び出し
ipcMain.handle('show-dialog', async () => {
  const result = await dialog.showMessageBox({
    type: 'info',
    title: 'メインプロセスから',
    message: 'これはメインプロセスが表示するダイアログです!'
  })
  return result.response
})

// ライフサイクル
app.whenReady().then(() => {
  createWindow()
  createMenu()
  createTray()
  registerShortcuts()
})

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

preload.js(安全なブリッジ)

例

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

contextBridge.exposeInMainWorld('electronAPI', {
  showDialog: () => ipcRenderer.invoke('show-dialog')
})

index.html(フロントエンド画面)

例

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>Electron ネイティブ機能デモ</title>
  <style>
    body { font-family: sans-serif; text-align: center; margin-top: 80px; }
    button { padding: 10px 20px; margin: 10px; font-size: 16px; cursor: pointer; }
    #filePath { color: #666; font-size: 14px; }
  </style>
</head>
<body>
  <h1>Electron ネイティブ機能デモ</h1>
  <p><button id="dialogBtn">ダイアログを表示</button></p>
  <p id="filePath"></p>

  <script>
    document.getElementById('dialogBtn').addEventListener('click', async () => {
      await window.electronAPI.showDialog()
    })

    const filePathEl = document.getElementById('filePath')
    window.electronAPI && window.electronAPI.fileOpened && window.electronAPI.fileOpened((path) => {
filePathEl.textContent = '開いたファイルのパス:' + path
   })
 </script>
</body>
</html>

実行npm startした後、機能は以下のとおりです:

  • 上部メニューバーに「ファイル」、「ツール」メニューが含まれています。
  • 「ファイル」→ ファイルを開く / ファイルを保存 でシステムダイアログが表示されます。
  • 「ツール」→ システム通知の表示、「バージョン情報」ウィンドウの表示。
  • トレイ領域にアプリアイコンが表示され、右クリックでメニューを表示できます。
  • ウィンドウを閉じるとトレイに最小化されます。
  • グローバルショートカットキーの登録CmdOrCtrl+Shift+I開発者ツールを開きます。
その他の拡張