关于vue.js:Electron之Main有什么关系

8次阅读

共计 10748 个字符,预计需要花费 27 分钟才能阅读完成。

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>

Download Image</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 <script>document.write(process.versions.node)</script>,

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

<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 <script>document.write(process.versions.node)</script>,

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

<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()

})

正文完
 0