web前端培訓分享Electron之Main Process API

千鋒武漢發表於2021-06-22

本節由小千給大家分享Electron使用指南之Main Process API,Electron API (Electron API 有三種) Main Process (主進程式) Renderer Process(渲染程式) Share Modules(共享模組)

App

事件

ready:

當 Electron 完成初始化時被觸發。

兩種使用方法 

app.on('ready', createWindow)

app.on('ready', () => {

console.log('App is ready!')

createWindow()

})

檢查應用是否登入:app.isReady()

如果應用沒有Ready,app.isReady()的值為 false

console.log('應用是否登入:' + app.isReady())

此時應用應該已經Ready

setTimeout(() => {

console.log('應用是否登入:' + app.isReady())

}, 2000)

before-quit

在應用程式開始關閉視窗之前觸發。

app.on('before-quit', (e) => {

console.log('App is quiting')

e.preventDefault()

})

browser-window-blur

在 browserWindow 失去焦點時發出

app.on('browser-window-blur', (e) => {

console.log('App unfocused')

})

browser-window-focus

在 browserWindow 獲得焦點時發出

app.on('browser-window-focus', (e) => {

console.log('App focused')

})

方法

app.quit()

app.on('browser-window-blur', (e) => {

setTimeout(() => {

app.quit()

}, 3000)

})

app.on('browser-window-blur', (e) => {

setTimeout(app.quit, 3000)

})

app.getPath(name)

app.on('ready', () => {

console.log(app.getPath('desktop'))

console.log(app.getPath('music'))

console.log(app.getPath('temp'))

console.log(app.getPath('userData'))

createWindow()

})

BrowserWindow

electron.BrowserWindow: 建立和控制瀏覽器視窗

例項方法

win.loadURL(url[, options]): 和 loadFile 互斥

mainWindow.loadURL(')

優雅的顯示視窗

使用ready-to-show事件

let mainWindow = new BrowserWindow({ show: false })

mainWindow.once('ready-to-show', () => {

mainWindow.show()

})

設定 backgroundColor

let win = new BrowserWindow({ backgroundColor: '#2e2c29' })

父子視窗

視窗定義

secondaryWindow = new BrowserWindow({

width: 600,

height: 600,

webPreferences: { nodeIntegration: true }

})

secondaryWindow.loadFile('index.html')

secondaryWindow.on('closed',  () => {

mainWindow = null

})

視窗關係

secondaryWindow = new BrowserWindow({

parent: mainWindon, // 定義父視窗

modal: true // 鎖定在主視窗

})

子視窗顯示和隱藏

secondaryWindow = new BrowserWindow({

show: false

})

setTimeout(() => {

secondaryWindow.show()

setTimeout(() => {

secondaryWindow.hide()

}, 3000)

}, 2000)

無邊框視窗

Frameless Window

mainWindow = new BrowserWindow({

frame: false

})

讓頁面可拖拽

<body style="user-select: none; -webkit-app-region:drag;">

no-drag 修復下面控制元件的bug

<input style="-webkit-app-region: no-drag;" type="range" name="range" min="0" max="10">

顯示紅綠燈

mainWindow = new BrowserWindow({

titleBarStyle: 'hidden' // or hiddenInset 距離紅綠燈更近

})

屬性與方法

minWidth && minHeight

mainWindow = new BrowserWindow({

minWidth: 300,

minHeight: 300

})

視窗焦點事件

secWindow = new BrowserWindow({

width: 400, height: 300,

webPreferences: { nodeIntegration: true },

})

mainWindow.on('focus', () => {

console.log('mainWindow focused')

})

secWindow.on('focus', () => {

console.log('secWindow focused')

})

app.on('browser-window-focus', () => {

console.log('App focused')

})

靜態方法

getAllWindows()

let allWindows = BrowserWindow.getAllWindows()

console.log(allWindows)

例項屬性

id

console.log(secWindow.id)

例項方法

maximize()secWindow.on('closed', () => { mainWindow.maximize() })

state

electron-window-state 儲存視窗的狀態 npm install electron-window-state 

webContents

webContents 是 EventEmitter 的例項, 負責渲染和控制網頁, 是 BrowserWindow 物件的一個屬性。 let wc = mainWindow.webContents console.log(wc)

方法 getAllWebContents()

返回 WebContents[] - 所有 WebContents 例項的陣列。 包含所有Windows,webviews,opened devtools 和 devtools 擴充套件背景頁的 web 內容const {app, BrowserWindow, webContents} = require('electron') console.log(webContents.getAllWebContents())

例項事件

did-finish-load

dom-ready

<div>

<img src=" alt="">

</div>

<script>

let wc = mainWindow.webContents

wc.on('did-finish-load', () => {

console.log('Conent fully loaded')

})

wc.on('dom-ready', () => {

console.log('DOM Ready')

})

</script>

new-window

<div>

<a target="_blank" href="><h3>Kitten</h3></a>

</div>

<script>

wc.on('new-window', (e, url) => {

e.preventDefault()

console.log('DOM Ready')

})

</script>

before-input-event

wc.on('before-input-event', (e, input) => {

console.log(`${input.key} : ${input.type}`)

})

login

did-navigate

mainWindow.loadURL(')

wc.on('login', (e, request, authInfo, callback) => {

console.log('Logging in:')

callback('user', 'passwd')

})

wc.on('did-navigate', (e, url, statusCode, message) => {

console.log(`Navigated to: ${url}, with response code: ${statusCode}`)

console.log(message)

})

media-started-playing

media-paused

<div>

<video src="./mgm.mp4" controls width="400"></video>

</div>

<script>

wc.on('media-started-playing', () => {

console.log('Video Started')

})

wc.on('media-paused', () => {

console.log('Video Paused')

})

</script>

context-menu : 右鍵上下文資訊

wc.on('context-menu', (e, params) => {

console.log(`Context menu opened on: ${params.mediaType} at x:${params.x}, y:${params.y}`)

})

wc.on('context-menu', (e, params) => {

console.log(`User seleted text: ${params.selectionText}`)

console.log(`Selection can be copied: ${params.editFlags.canCopy}`)

})

例項方法

executeJavaScript()

wc.on('context-menu', (e, params) => {

wc.executeJavaScript(`alert('${params.selectionText}')`)

})

Session

管理瀏覽器會話、cookie、快取、代理設定等。

起步

建立session物件

let session = mainWindow.webContents.session

console.log(session) // {}

在chromium 建立localStorage,然後建立兩個視窗,兩個session共享

mainWindow = new BrowserWindow({

width: 1000, height: 800,

webPreferences: { nodeIntegration: true }

})

secWindow = new BrowserWindow({

width: 500, height: 400,

webPreferences: { nodeIntegration: true }

})

let session = mainWindow.webContents.session

let session2 = mainWindow.webContents.session

console.log(Object.is(session, session2)) // true

// Load index.html into the new BrowserWindow

mainWindow.loadFile('index.html')

secWindow.loadFile('index.html')

// Open DevTools - Remove for PRODUCTION!

mainWindow.webContents.openDevTools();

secWindow.webContents.openDevTools();

// Listen for window being closed

mainWindow.on('closed',  () => {

mainWindow = null

})

secWindow.on('closed',  () => {

secWindow = null

})

defaultSession

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

let ses = mainWindow.webContents.session

console.log(Object.is(session.defaultSession, ses)) // true

自定義session

let customSes = session.fromPartition('part1')

console.log(Object.is(customSes, ses)) //false, 此時customSes 還是共享session

secWindow = new BrowserWindow({

width: 500, height: 400,

webPreferences: {

nodeIntegration: true,

session: customSes // 定義session, 此時子視窗有自己的session

}

})

// 在子視窗裡建立localstorge: winName/secWindow

// 關閉所有視窗,發現建立的localstorage又消失了,因為此時的session儲存在記憶體裡,重新啟動應用又消失了。可以加字首persist,使其變為永久儲存:

let customSes = session.fromPartition('persist:part1')

// 或者:

secWindow = new BrowserWindow({

width: 500, height: 400,

webPreferences: {

nodeIntegration: true,

- session: customSes

+ partition: 'persist:part1'

}

})

例項方法

ses.clearStorageData() // 刪除主視窗的的storage

cookie

查詢和修改一個會話的cookies

// 查詢所有 cookies

session.defaultSession.cookies.get({})

.then((cookies) => {

console.log(cookies)

}).catch((error) => {

console.log(error)

})

// 查詢所有與設定的 URL 相關的所有 cookies

session.defaultSession.cookies.get({ url: ' })

.then((cookies) => {

console.log(cookies)

}).catch((error) => {

console.log(error)

})

// 設定一個 cookie,使用設定的名稱;

// 如果存在,則會覆蓋原先 cookie.

const cookie = { url: ', name: 'dummy_name', value: 'dummy' }

session.defaultSession.cookies.set(cookie)

.then(() => {

// success

}, (error) => {

console.error(error)

})

downloadItem

控制來自於遠端資源的檔案下載。

<h2><a href=" download>Download Image</a></h2>

<progress value="0" max="100" id="progress"></progress>

<script>

window.progress = document.getElementById('progress')

</script>

// main.js

let ses = session.defaultSession

ses.on('will-download', (e, downloadItem, webContents) => {

let fileName = downloadItem.getFilename()

let fileSize = downloadItem.getTotalBytes()

// Save to desktop

downloadItem.setSavePath(app.getPath('desktop') + `/${fileName}`)

downloadItem.on('updated', (e, state) => {

let received = downloadItem.getReceivedBytes()

if (state === 'progressing' && received) {

let progress = Math.round((received/fileSize)*100)

webContents.executeJavaScript(`window.progress.value = ${progress}`)

}

})

})

dialog - 對話方塊

顯示用於開啟和儲存檔案、警報等的本機系統對話方塊

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

mainWindow.webContents.on('did-finish-load', () => {

dialog.showOpenDialog({

buttonLabel: '選擇',

defaultPath: app.getPath('desktop'),

properties: ['multiSelections', 'createDirectory', 'openFile', 'openDirectory']

}, filepaths => {

console.log(filepaths)

})

})

dialog.showSaveDialog({}, filename => {

console.log(filename)

})

const answers = ['Yes', 'No', 'Maybe']

dialog.showMessageBox({

title: 'Message Box',

message: 'Please select an option',

detail: 'Message details.',

buttons: answers

}, response => {

console.log(`User selected: ${answers[response]}`)

})

快捷鍵+系統快捷鍵

快捷鍵:定義鍵盤快捷鍵。  系統快捷鍵:在應用程式沒有鍵盤焦點時,監聽鍵盤事件。

快捷鍵可以包含多個功能鍵和一個鍵碼的字串,由符號+結合,用來定義你應用中的鍵盤快捷鍵

示例: 

CommandOrControl+A

CommandOrControl+Shift+Z

快捷方式使用 register 方法在 globalShortcut 模組中註冊。

globalShortcut 模組可以在作業系統中註冊/登出全域性快捷鍵, 以便可以為操作定製各種快捷鍵。

注意: 快捷方式是全域性的; 即使應用程式沒有鍵盤焦點, 它也仍然在持續監聽鍵盤事件。 在應用程式模組發出 ready 事件之前, 不應使用此模組。

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

globalShortcut.register('G', () => {

console.log('User pressed G')

})

globalShortcut.register('CommandOrControl+Y', () => {

console.log('User pressed G with a combination key')

globalShortcut.unregister('CommandOrControl+G')

})

Menu

1、index.html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">

<title>Hello World!</title>

</head>

<body>

<h1>Hello World!</h1>

<textarea name="name" rows="8" cols="80"></textarea>

<!-- All of the Node.js APIs are available in this renderer process. -->

We are using Node.js <strong><script>document.write( process.versions.node)</script></strong>,

and Electron <strong><script>document.write( process.versions.electron )</script></strong>.

<script>

// You can also require other files to run in this process

require('./renderer.js')

</script>

</body>

</html>

2、main.js

// Modules

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

// Keep a global reference of the window object, if you don't, the window will

// be closed automatically when the JavaScript object is garbage collected.

let mainWindow

let mainMenu = Menu.buildFromTemplate( require('./mainMenu') )

// Create a new BrowserWindow when `app` is ready

function createWindow () {

mainWindow = new BrowserWindow({

width: 1000, height: 800,

webPreferences: { nodeIntegration: true }

})

// Load index.html into the new BrowserWindow

mainWindow.loadFile('index.html')

// Open DevTools - Remove for PRODUCTION!

mainWindow.webContents.openDevTools();

Menu.setApplicationMenu(mainMenu)

// Listen for window being closed

mainWindow.on('closed',  () => {

mainWindow = null

})

}

// Electron `app` is ready

app.on('ready', createWindow)

// Quit when all windows are closed - (Not macOS - Darwin)

app.on('window-all-closed', () => {

if (process.platform !== 'darwin') app.quit()

})

// When app icon is clicked and app is running, (macOS) recreate the BrowserWindow

app.on('activate', () => {

if (mainWindow === null) createWindow()

})

3、mainMenu.js

module.exports = [

{

label: 'Electron',

submenu: [

{ label: 'Item 1'},

{ label: 'Item 2', submenu: [ { label: 'Sub Item 1'} ]},

{ label: 'Item 3'},

]

},

{

label: 'Edit',

submenu: [

{ role: 'undo'},

{ role: 'redo'},

{ role: 'copy'},

{ role: 'paste'},

]

},

{

label: 'Actions',

submenu: [

{

label: 'DevTools',

role: 'toggleDevTools'

},

{

role: 'toggleFullScreen'

},

{

label: 'Greet',

click: () => { console.log('Hello from Main Menu') },

accelerator: 'Shift+Alt+G'

}

]

}

]

Context Menus

1、index.html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">

<title>Hello World!</title>

</head>

<body>

<h1>Hello World!</h1>

<textarea name="name" rows="8" cols="80"></textarea>

<!-- All of the Node.js APIs are available in this renderer process. -->

We are using Node.js <strong><script>document.write( process.versions.node)</script></strong>,

and Electron <strong><script>document.write( process.versions.electron )</script></strong>.

<script>

// You can also require other files to run in this process

require('./renderer.js')

</script>

</body>

</html>

2、main.js

// Modules

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

// Keep a global reference of the window object, if you don't, the window will

// be closed automatically when the JavaScript object is garbage collected.

let mainWindow

let contextMenu = Menu.buildFromTemplate([

{ label: 'Item 1' },

{ role: 'editMenu' }

])

// Create a new BrowserWindow when `app` is ready

function createWindow () {

mainWindow = new BrowserWindow({

width: 1000, height: 800,

webPreferences: { nodeIntegration: true }

})

// Load index.html into the new BrowserWindow

mainWindow.loadFile('index.html')

// Open DevTools - Remove for PRODUCTION!

mainWindow.webContents.openDevTools();

mainWindow.webContents.on('context-menu', e => {

contextMenu.popup()

})

// Listen for window being closed

mainWindow.on('closed',  () => {

mainWindow = null

})

}

// Electron `app` is ready

app.on('ready', createWindow)

// Quit when all windows are closed - (Not macOS - Darwin)

app.on('window-all-closed', () => {

if (process.platform !== 'darwin') app.quit()

})

// When app icon is clicked and app is running, (macOS) recreate the BrowserWindow

app.on('activate', () => {

if (mainWindow === null) createWindow()

})

Tray (托盤)

1、main.js

// Modules

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

// Keep a global reference of the window object, if you don't, the window will

// be closed automatically when the JavaScript object is garbage collected.

let mainWindow, tray

let trayMenu = Menu.buildFromTemplate([

{ label: 'Item 1' },

{ role: 'quit' }

])

function createTray() {

tray = new Tray('trayTemplate@2x.png')

tray.setToolTip('Tray details')

tray.on('click', e => {

if (e.shiftKey) {

app.quit()

} else {

mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()

}

})

tray.setContextMenu(trayMenu)

}

// Create a new BrowserWindow when `app` is ready

function createWindow () {

createTray()

mainWindow = new BrowserWindow({

width: 1000, height: 800,

webPreferences: { nodeIntegration: true }

})

// Load index.html into the new BrowserWindow

mainWindow.loadFile('index.html')

// Open DevTools - Remove for PRODUCTION!

mainWindow.webContents.openDevTools();

// Listen for window being closed

mainWindow.on('closed',  () => {

mainWindow = null

})

}

// Electron `app` is ready

app.on('ready', createWindow)

// Quit when all windows are closed - (Not macOS - Darwin)

app.on('window-all-closed', () => {

if (process.platform !== 'darwin') app.quit()

})

// When app icon is clicked and app is running, (macOS) recreate the BrowserWindow

app.on('activate', () => {

if (mainWindow === null) createWindow()

})

powerMonitor (電源指示器)

// Modules

const electron = require('electron')

const {app, BrowserWindow} = electron

// Keep a global reference of the window object, if you don't, the window will

// be closed automatically when the JavaScript object is garbage collected.

let mainWindow

// Create a new BrowserWindow when `app` is ready

function createWindow () {

mainWindow = new BrowserWindow({

width: 1000, height: 800,

webPreferences: { nodeIntegration: true }

})

// Load index.html into the new BrowserWindow

mainWindow.loadFile('index.html')

// Open DevTools - Remove for PRODUCTION!

mainWindow.webContents.openDevTools();

// Listen for window being closed

mainWindow.on('closed',  () => {

mainWindow = null

})

electron.powerMonitor.on('resume', e => {

if(!mainWindow) createWindow()

})

electron.powerMonitor.on('suspend', e => {

console.log('Saving some data')

})

}

// Electron `app` is ready

app.on('ready', createWindow)

// Quit when all windows are closed - (Not macOS - Darwin)

app.on('window-all-closed', () => {

if (process.platform !== 'darwin') app.quit()

})

// When app icon is clicked and app is running, (macOS) recreate the BrowserWindow

app.on('activate', () => {

if (mainWindow === null) createWindow()

})

本文來自千鋒教育,轉載請註明出處。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31548651/viewspace-2777744/,如需轉載,請註明出處,否則將追究法律責任。

相關文章