Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Electron Native Feature Integration

Electron Native Feature Integration

Electron is powerful because it can not only write front ends but also access native system features such as menus, dialogs, trays, notifications, and global shortcuts.

In this chapter we look at how to call these features through main process modules.


Menu system

Electron provides Menu The module is used to create menu bars, context menus, and system tray menus.

Application menu (Menu)

The application menu is the menu bar shown at the top of the window (macOS) or in the app window.

Example

const

{

app

,

Menu

}

=

require

(

'electron'

)

const

template

=

[

 

{

    label

:

'File'

,

    submenu

:

[

     

{

label

:

'New File'

,

accelerator

:

'CmdOrCtrl+N'

,

click

:

(

)

=>

console.

log

(

'New File'

)

}

,

     

{

label

:

'Open...'

,

accelerator

:

'CmdOrCtrl+O'

}

,

     

{

type

:

'separator'

}

,

     

{

label

:

'Exit'

,

role

:

'quit'

}

   

]

 

}

,

 

{

    label

:

'Edit'

,

    submenu

:

[

     

{

role

:

'undo'

}

,

     

{

role

:

'redo'

}

,

     

{

type

:

'separator'

}

,

     

{

role

:

'cut'

}

,

     

{

role

:

'copy'

}

,

     

{

role

:

'paste'

}

   

]

 

}

]

const

menu

=

Menu.

buildFromTemplate

(

template

)

Menu.

setApplicationMenu

(

menu

)

Explanation:

Context menu (Context Menu)

The right-click menu is usually triggered in the renderer process:

Example

// main.js

const

{

ipcMain

,

Menu

}

=

require

(

'electron'

)

ipcMain.

on

(

'show-context-menu'

,

(

event

)

=>

{

 

const

menu

=

Menu.

buildFromTemplate

(

[

   

{

label

:

'Refresh'

,

click

:

(

)

=>

event.

sender

.

reload

(

)

}

,

   

{

label

:

'Copy'

,

role

:

'copy'

}

,

   

{

label

:

'Paste'

,

role

:

'paste'

}

 

]

)

  menu.

popup

(

)

}

)

Example

// renderer.js

window.

addEventListener

(

'contextmenu'

,

(

e

)

=>

{

  e.

preventDefault

(

)

  window.

electronAPI

.

showContextMenu

(

)

}

)

System tray menu

Show an icon and menu in the system notification area.

Example

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

:

'Open Main Window'

,

click

:

(

)

=>

mainWindow.

show

(

)

}

,

   

{

label

:

'Exit'

,

click

:

(

)

=>

app.

quit

(

)

}

 

]

)

  tray.

setToolTip

(

'My Electron App'

)

  tray.

setContextMenu

(

contextMenu

)

}

Menu shortcuts

Pass accelerator define them. For example:

{ label: '保存', accelerator: 'CmdOrCtrl+S', click: saveFile }


System dialogs

dialog The module provides native system dialogs for files, messages, errors, etc.

File/folder selection

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)

}

Save dialog

async function saveFileDialog() {

  const result = await dialog.showSaveDialog({

    title: '保存文件',

    defaultPath: '新建文档.txt'

  })

  console.log(result.filePath)

}

Message/error dialog



dialog.showMessageBox({

  type: 'info',

  title: '提示',

  message: '操作已完成!'

})



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


System tray

The tray (Tray) lets the app still interact via a system icon while running in the background.

Create a tray icon

const { Tray } = require('electron')

const path = require('path')



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

Tray menu and tooltip



const contextMenu = Menu.buildFromTemplate([

  { label: '显示窗口', click: () => mainWindow.show() },

  { label: '退出', click: () => app.quit() }

])

tray.setToolTip('Electron 应用运行中')

tray.setContextMenu(contextMenu)

Tray notifications



tray.displayBalloon({

  icon: path.join(__dirname, 'icon.png'),

  title: '新消息',

  content: '您有一条新通知'

})

Minimize to tray

Listen for the close event to hide the window:

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

  event.preventDefault()

  mainWindow.hide()

})


Notifications

Electron's Notification class can display system notifications across platforms.

Sending system notifications

new Notification({

  title: '任务完成',

  body: '您的文件已下载完成'

}).show()

Notification interaction handling

const notif = new Notification({ title: '点击通知', body: '点击我触发事件' })

notif.on('click', () => {

  console.log('用户点击了通知')

})

notif.show()

Cross-platform compatibility


Global shortcuts

Pass globalShortcut Register system-level hotkeys.

Register global shortcuts



const { globalShortcut } = require('electron')



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

  globalShortcut.register('CmdOrCtrl+Shift+I', () => {

    console.log('快捷键触发:打开调试工具')

    mainWindow.webContents.openDevTools()

  })

})

Handling shortcut conflicts

You can check before registering:

if (globalShortcut.isRegistered('CmdOrCtrl+Shift+I')) {

  console.log('快捷键已被占用')

}

Handling platform differences

You can use conditional checks:

const shortcut = process.platform === 'darwin' ? 'Cmd+Shift+T' : 'Ctrl+Shift+T'

globalShortcut.register(shortcut, () => console.log('快捷键触发'))


Summary

Function module Typical use
The menu Menu Application menus, right-click menus, tray menus
Dialogs dialog Open files, save files, show prompts or errors
Tray Tray Background running, system status display
Notification Notification Show event progress, system reminders
Global shortcuts globalShortcut Register system-level quick actions

Electron Native Features Demo Project

Project Structure

my-electron-native-demo/

├── package.json

├── main.js             # 主进程逻辑

├── preload.js          # 预加载脚本(安全通信)

└── index.html          # 主界面

package.json

Note: do not write comments in JSON files (otherwise an EJSONPARSE error occurs)

{

  "name": "my-electron-native-demo",

  "version": "1.0.0",

  "description": "Electron 原生功能演示项目",

  "main": "main.js",

  "scripts": {

    "start": "electron ."

  },

  "devDependencies": {

    "electron": "latest"

  }

}

Install dependencies:



npm install

Start the app:



npm start

main.js (main process)

Example

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'

)

 

// Show after the page finishes loading

  mainWindow.

once

(

'ready-to-show'

,

(

)

=>

mainWindow.

show

(

)

)

 

// Listen for window close: minimize to tray

  mainWindow.

on

(

'close'

,

(

event

)

=>

{

    event.

preventDefault

(

)

    mainWindow.

hide

(

)

 

}

)

}

function

createMenu

(

)

{

 

const

template

=

[

   

{

      label

:

'File'

,

      submenu

:

[

       

{

label

:

'Open file'

,

click

:

openFile

}

,

       

{

label

:

'Save file'

,

click

:

saveFile

}

,

       

{

type

:

'separator'

}

,

       

{

label

:

'Exit'

,

click

:

(

)

=>

app.

quit

(

)

}

     

]

   

}

,

   

{

      label

:

'Tools'

,

      submenu

:

[

       

{

label

:

'Show Notification'

,

click

:

showNotification

}

,

       

{

label

:

'About'

,

click

:

showAbout

}

     

]

   

}

 

]

 

const

menu

=

Menu.

buildFromTemplate

(

template

)

  Menu.

setApplicationMenu

(

menu

)

}

function

createTray

(

)

{

 

const

icon

=

path.

join

(

__dirname

,

'icon.png'

)

 

// Please prepare a 16x16 or 32x32 icon

  tray

=

new

Tray

(

icon

)

 

const

contextMenu

=

Menu.

buildFromTemplate

(

[

   

{

label

:

'Show Window'

,

click

:

(

)

=>

mainWindow.

show

(

)

}

,

   

{

label

:

'Exit'

,

click

:

(

)

=>

app.

quit

(

)

}

 

]

)

  tray.

setToolTip

(

'Electron Native Features Demo'

)

  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

:

'Text file'

,

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

:

'Save file'

,

    defaultPath

:

'New Document.txt'

 

}

)

 

if

(

!

result.

canceled

)

{

    dialog.

showMessageBox

(

{

type

:

'info'

,

message

:

`The file will be saved to: $

{

result.

filePath

}

`

}

)

 

}

}

function

showNotification

(

)

{

 

const

notif

=

new

Notification

(

{

    title

:

'Electron Notification'

,

    body

:

'This is a system notification!'

 

}

)

  notif.

on

(

'click'

,

(

)

=>

{

    dialog.

showMessageBox

(

{

message

:

'You clicked the notification!'

}

)

 

}

)

  notif.

show

(

)

}

function

showAbout

(

)

{

  dialog.

showMessageBox

(

{

    type

:

'info'

,

    title

:

'About'

,

    message

:

'Electron Native Features Demo Project\nVersion: 1.0.0'

 

}

)

}

// Renderer process call

ipcMain.

handle

(

'show-dialog'

,

async

(

)

=>

{

 

const

result

=

await dialog.

showMessageBox

(

{

    type

:

'info'

,

    title

:

'From the main process'

,

    message

:

'This is a dialog shown by the main process!'

 

}

)

 

return

result.

response

}

)

// Lifecycle

app.

whenReady

(

)

.

then

(

(

)

=>

{

  createWindow

(

)

  createMenu

(

)

  createTray

(

)

  registerShortcuts

(

)

}

)

app.

on

(

'window-all-closed'

,

(

)

=>

{

 

if

(

process.

platform

!==

'darwin'

)

app.

quit

(

)

}

)

preload.js (security bridge)

Example

const

{

contextBridge

,

ipcRenderer

}

=

require

(

'electron'

)

contextBridge.

exposeInMainWorld

(

'electronAPI'

,

{

  showDialog

:

(

)

=>

ipcRenderer.

invoke

(

'show-dialog'

)

}

)

index.html (front-end UI)

Example

 

 

<p>Electron Native Features Demo</p>

 

 

Electron Native Features Demo

 

 

 

Run npm start After that, the features are as follows: