日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > HTML >内容正文

HTML

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

發(fā)布時(shí)間:2024/9/30 HTML 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 web前端培训分享Electron之Main Process API 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本節(jié)由千鋒web前端培訓(xùn)機(jī)構(gòu)講師給大家分享Electron使用指南之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

})

窗口焦點(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)

實(shí)例屬性

id

console.log(secWindow.id)

實(shí)例方法

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

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-loaddom-ready<div><img src="https://placekitten.com/500/500" alt=""></div><script>let wc = mainWindow.webContentswc.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="https://placekitten.com/500/500"><h3>Kitten</h3></a></div><script>wc.on('new-window', (e, url) => {e.preventDefault()console.log('DOM Ready')})</script>before-input-eventwc.on('before-input-event', (e, input) => {console.log(`${input.key} : ${input.type}`)})logindid-navigatemainWindow.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-playingmedia-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

// 查詢所有 cookiessession.defaultSession.cookies.get({}).then((cookies) => {console.log(cookies)}).catch((error) => {console.log(error)})// 查詢所有與設(shè)置的 URL 相關(guān)的所有 cookiessession.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 href="https://picsum.photos/5000/5000/" download>Download Image</a></h2><progress value="0" max="100" id="progress"></progress><script>window.progress = document.getElementById('progress')</script>// main.jslet ses = session.defaultSessionses.on('will-download', (e, downloadItem, webContents) => {let fileName = downloadItem.getFilename()let fileSize = downloadItem.getTotalBytes()// Save to desktopdownloadItem.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 processrequire('./renderer.js')</script></body></html>

2、main.js

// Modulesconst {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 mainWindowlet mainMenu = Menu.buildFromTemplate( require('./mainMenu') )// Create a new BrowserWindow when `app` is readyfunction createWindow () {mainWindow = new BrowserWindow({width: 1000, height: 800,webPreferences: { nodeIntegration: true }})// Load index.html into the new BrowserWindowmainWindow.loadFile('index.html')// Open DevTools - Remove for PRODUCTION!mainWindow.webContents.openDevTools();Menu.setApplicationMenu(mainMenu)// Listen for window being closedmainWindow.on('closed', () => {mainWindow = null})}// Electron `app` is readyapp.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 BrowserWindowapp.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 processrequire('./renderer.js')</script></body></html>

2、main.js

// Modulesconst {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 mainWindowlet contextMenu = Menu.buildFromTemplate([{ label: 'Item 1' },{ role: 'editMenu' }])// Create a new BrowserWindow when `app` is readyfunction createWindow () {mainWindow = new BrowserWindow({width: 1000, height: 800,webPreferences: { nodeIntegration: true }})// Load index.html into the new BrowserWindowmainWindow.loadFile('index.html')// Open DevTools - Remove for PRODUCTION!mainWindow.webContents.openDevTools();mainWindow.webContents.on('context-menu', e => {contextMenu.popup()})// Listen for window being closedmainWindow.on('closed', () => {mainWindow = null})}// Electron `app` is readyapp.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 BrowserWindowapp.on('activate', () => {if (mainWindow === null) createWindow()})

Tray (托盤)

1、main.js

// Modulesconst {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, traylet 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 readyfunction createWindow () {createTray()mainWindow = new BrowserWindow({width: 1000, height: 800,webPreferences: { nodeIntegration: true }})// Load index.html into the new BrowserWindowmainWindow.loadFile('index.html')// Open DevTools - Remove for PRODUCTION!mainWindow.webContents.openDevTools();// Listen for window being closedmainWindow.on('closed', () => {mainWindow = null})}// Electron `app` is readyapp.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 BrowserWindowapp.on('activate', () => {if (mainWindow === null) createWindow()})powerMonitor (電源指示器)// Modulesconst 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 readyfunction createWindow () {mainWindow = new BrowserWindow({width: 1000, height: 800,webPreferences: { nodeIntegration: true }})// Load index.html into the new BrowserWindowmainWindow.loadFile('index.html')// Open DevTools - Remove for PRODUCTION!mainWindow.webContents.openDevTools();// Listen for window being closedmainWindow.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 readyapp.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 BrowserWindowapp.on('activate', () => {if (mainWindow === null) createWindow()})

本文來自千鋒教育,轉(zhuǎn)載請(qǐng)注明出處。

總結(jié)

以上是生活随笔為你收集整理的web前端培训分享Electron之Main Process API的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 国产免费黄色小视频 | 日本精品999| 久久艹在线 | 69久人妻无码精品一区 | 亚洲精品女| 日韩亚洲影院 | 免费成年人视频在线观看 | 日本在线视频一区 | 日韩高清片 | 成人黄色一区二区三区 | 香蕉网在线视频 | 国产激情影院 | 国产精品福利在线 | 日韩电影一区 | 色无五月| 神马午夜国产 | 日韩欧美aaa | 午夜免费网| 亚洲男人天堂久久 | 免费看黄色一级片 | 日韩免费中文字幕 | 国产av成人一区二区三区高清 | 欧美 日韩 中文字幕 | 久久久久久一区二区三区 | 老女人综合网 | 亚洲色域网| 1769国产精品视频 | 欧美日韩综合一区二区三区 | av大全在线| 成人免费无遮挡无码黄漫视频 | 黑丝美女啪啪 | 成人动漫在线播放 | 久热精品免费视频 | 免费午夜影院 | 青青草成人免费在线视频 | 毛茸茸亚洲孕妇孕交片 | 天天爱夜夜操 | 亚洲毛片在线看 | 日韩成人av片 | 黄色成年人网站 | 国产免费视频 | 看黄色a级片 | 日本久久不卡 | 国产久操视频 | 男同互操gay射视频在线看 | 91淫黄大片 | 一品道av | 国内成人精品 | 婷婷色婷婷开心五月四房播播 | 久久黄色免费视频 | 亚洲四虎影院 | 亚洲精品中文字幕在线观看 | 亚洲精品国产成人av在线 | 熟妇高潮喷沈阳45熟妇高潮喷 | 欧美毛片在线 | 四虎影成人精品a片 | 日韩在线一二 | 波多野结衣视频免费在线观看 | www.成人.com | 黄色免费视频观看 | 精品国产aⅴ一区二区三区四川人 | 少妇性bbb搡bbb爽爽爽欧美 | 一区二区三区在线免费观看视频 | 九一精品在线 | 午夜在线播放 | 亚洲视频色图 | 欧美又粗又大xxxxbbbb疯狂 | 成年人性视频 | 久久理论片 | 国产盗摄一区二区 | 午夜天堂视频 | 天天爽夜夜爽夜夜爽精品 | 在线观看9.1 | 亚洲第一区视频 | 亚洲国产日韩一区无码精品久久久 | 日本一区二区三区在线看 | av免费看片 | 国产影视av | 日本一道在线 | 九九天堂网 | 久久99伊人 | 正在播放老肥熟妇露脸 | 娇妻之欲海泛舟无弹窗笔趣阁 | 天堂精品一区 | 黄色三级免费观看 | 寻找身体恐怖电影免费播放 | 你懂的网站在线观看 | 你懂的网址在线观看 | 日韩欧美一级大片 | 成人性生交大免费看 | 久久福利免费视频 | 亚洲一区二区三区午夜 | 欧美一区二区性久久久 | 瑟瑟视频在线 | 国产午夜在线视频 | 黄色aaa大片 | 国产资源免费 | 国产福利久久久 | www.youjizz国产|