Electron使用指南 - [03] Main Process API

Main Process API

Electron API (Electron API 有三種)
Main Process (主進(jìn)進(jìn)程)
Renderer Process(渲染進(jìn)程)
Share Modules(共享模塊)

App

事件

ready:

當(dāng) Electron 完成初始化時(shí)被觸發(fā)。

  • 兩種使用方法
app.on('ready', createWindow)
app.on('ready', () => {
  console.log('App is ready!')
  createWindow()
})
  • 檢查應(yīng)用是否登錄:app.isReady()
  • 如果應(yīng)用沒有Ready,app.isReady()的值為 false
console.log('應(yīng)用是否登錄:' + app.isReady())
  • 此時(shí)應(yīng)用應(yīng)該已經(jīng)Ready
setTimeout(() => {
  console.log('應(yīng)用是否登錄:' + app.isReady())
}, 2000)

before-quit

在應(yīng)用程序開始關(guān)閉窗口之前觸發(fā)。

app.on('before-quit', (e) => {
  console.log('App is quiting')
  e.preventDefault()
})

browser-window-blur

在 browserWindow 失去焦點(diǎn)時(shí)發(fā)出

app.on('browser-window-blur', (e) => {
  console.log('App unfocused')
})

browser-window-focus

在 browserWindow 獲得焦點(diǎn)時(shí)發(fā)出

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: 創(chuàng)建和控制瀏覽器窗口

實(shí)例方法

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

mainWindow.loadURL('https://www.baidu.com')

優(yōu)雅的顯示窗口

  • 使用ready-to-show事件
let mainWindow = new BrowserWindow({ show: false })
mainWindow.once('ready-to-show', () => {
  mainWindow.show()
})
  • 設(shè)置 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
})
  • 窗口關(guān)系
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 修復(fù)下面控件的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
})

更多詳見:https://electronjs.org/docs/api/browser-window#new-browserwindowoptions

窗口焦點(diǎn)事件

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')
})

靜態(tài)方法

  • getAllWindows()
let allWindows = BrowserWindow.getAllWindows()
console.log(allWindows)

更多詳見: https://electronjs.org/docs/api/browser-window#%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95

實(shí)例屬性

  • id
console.log(secWindow.id)

更多詳見:https://electronjs.org/docs/api/browser-window#%E5%AE%9E%E4%BE%8B%E5%B1%9E%E6%80%A7

實(shí)例方法

state

electron-window-state 保存窗口的狀態(tài) npm install electron-window-state

webContents

webContents 是 EventEmitter 的實(shí)例, 負(fù)責(zé)渲染和控制網(wǎng)頁, 是 BrowserWindow 對(duì)象的一個(gè)屬性。
let wc = mainWindow.webContents console.log(wc)

方法 getAllWebContents()

  • 返回 WebContents[] - 所有 WebContents 實(shí)例的數(shù)組。 包含所有Windows,webviews,opened devtools 和 devtools 擴(kuò)展背景頁的 web 內(nèi)容const {app, BrowserWindow, webContents} = require('electron') console.log(webContents.getAllWebContents())

實(shí)例事件

  • did-finish-load
  • dom-ready
<div>
   <img src="https://placekitten.com/500/500" 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" ><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('https://httpbin.org/basic-auth/user/passwd')

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}`)
})

實(shí)例方法

  • executeJavaScript()
wc.on('context-menu', (e, params) => {
  wc.executeJavaScript(`alert('${params.selectionText}')`)
})

Session

管理瀏覽器會(huì)話、cookie、緩存、代理設(shè)置等。

起步

  • 創(chuàng)建session對(duì)象
let session = mainWindow.webContents.session
console.log(session) // {}
  • 在chromium 創(chuàng)建localStorage,然后創(chuàng)建兩個(gè)窗口,兩個(gè)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, 此時(shí)customSes 還是共享session

secWindow = new BrowserWindow({
  width: 500, height: 400,
  webPreferences: { 
    nodeIntegration: true,
    session: customSes // 定義session, 此時(shí)子窗口有自己的session
  }
})

// 在子窗口里創(chuàng)建localstorge: winName/secWindow
// 關(guān)閉所有窗口,發(fā)現(xiàn)創(chuàng)建的localstorage又消失了,因?yàn)榇藭r(shí)的session存儲(chǔ)在內(nèi)存里,重新啟動(dòng)應(yīng)用又消失了。可以加前綴persist,使其變?yōu)橛谰么鎯?chǔ):

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

// 或者:

secWindow = new BrowserWindow({
  width: 500, height: 400,
  webPreferences: { 
    nodeIntegration: true,
    - session: customSes
    + partition: 'persist:part1'
  }
})
  • 實(shí)例方法
ses.clearStorageData() // 刪除主窗口的的storage

cookie

查詢和修改一個(gè)會(huì)話的cookies

// 查詢所有 cookies
session.defaultSession.cookies.get({})
  .then((cookies) => {
    console.log(cookies)
  }).catch((error) => {
    console.log(error)
  })
// 查詢所有與設(shè)置的 URL 相關(guān)的所有 cookies
session.defaultSession.cookies.get({ url: 'http://www.github.com' })
  .then((cookies) => {
    console.log(cookies)
  }).catch((error) => {
    console.log(error)
  })
// 設(shè)置一個(gè) cookie,使用設(shè)置的名稱;
// 如果存在,則會(huì)覆蓋原先 cookie.
const cookie = { url: 'http://www.github.com', name: 'dummy_name', value: 'dummy' }
session.defaultSession.cookies.set(cookie)
  .then(() => {
    // success
  }, (error) => {
    console.error(error)
  })

downloadItem

控制來自于遠(yuǎn)程資源的文件下載。

<h2><a  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 - 對(duì)話框

顯示用于打開和保存文件、警報(bào)等的本機(jī)系統(tǒng)對(duì)話框

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]}`)
})

快捷鍵+系統(tǒng)快捷鍵

快捷鍵:定義鍵盤快捷鍵。 系統(tǒng)快捷鍵:在應(yīng)用程序沒有鍵盤焦點(diǎn)時(shí),監(jiān)聽鍵盤事件。

快捷鍵可以包含多個(gè)功能鍵和一個(gè)鍵碼的字符串,由符號(hào)+結(jié)合,用來定義你應(yīng)用中的鍵盤快捷鍵

示例:

  • CommandOrControl+A
  • CommandOrControl+Shift+Z

快捷方式使用 register 方法在 globalShortcut 模塊中注冊(cè)。

globalShortcut 模塊可以在操作系統(tǒng)中注冊(cè)/注銷全局快捷鍵, 以便可以為操作定制各種快捷鍵。

注意: 快捷方式是全局的; 即使應(yīng)用程序沒有鍵盤焦點(diǎn), 它也仍然在持續(xù)監(jiān)聽鍵盤事件。 在應(yīng)用程序模塊發(fā)出 ready 事件之前, 不應(yīng)使用此模塊。

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()
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容