日韩性视频-久久久蜜桃-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ò),歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 久久久电影 | 国产高潮又爽又无遮挡又免费 | 日韩一区二区三区电影 | 国产亚洲欧美日韩精品 | 亚洲国产97在线精品一区 | 成人精品视频网站 | 天天操天天操天天操 | 免费小视频在线观看 | 五级 黄 色 片 | 亚洲一区二区三区欧美 | 色漫| 国产精品第72页 | 国产美女无遮挡免费 | 亚洲天天干 | 看了让人下面流水的视频 | 亚洲国产精品女人久久久 | 亚洲视频一区二区三区在线观看 | 国产免费黄色片 | 性色av网站| av手机版| 婷婷中文 | 亚洲六月丁香色婷婷综合久久 | 亚洲成a人| 在线看国产 | 在线天堂1| 成人录像 | 在线视频一区二区 | 国产精品久久久久久亚洲色 | 丰满人妻一区二区三区免费 | 国产精品久久久久无码av | 欧美中文字幕在线 | 中文字幕永久在线观看 | 黑人中文字幕一区二区三区 | 怡红院成人在线 | 大胸美女无遮挡 | 欧美黄色一级大片 | 国产人人射 | 久久av网站 | 亚洲性xxxx | 一区二区视频国产 | 色呦呦在线看 | 久久99久久久| 三级特黄| 国产精品国产三级国产aⅴ无密码 | 他趴在我两腿中间添得好爽在线看 | 污污免费在线观看 | 欧美精品在线第一页 | 九色porny原创自拍 | 精品国产乱码久久久久久1区二区 | 91ts人妖另类精品系列 | 免费av网址大全 | 日韩久久一区 | 亚洲色图图片 | 手机av电影在线 | 成人黄色免费看 | 精品久久不卡 | 国产欧美精品aaaaaa片 | 精品久久人妻av中文字幕 | 婷婷激情六月 | 亚洲成av| 亚洲AV综合色区无码国产播放 | 一区二区三区欧美在线 | 秋霞黄色片 | 欧美国产高潮xxxx1819 | 欧美日韩3p| 亚洲成人免费观看 | 另类小说亚洲色图 | 国产一区二区三区在线观看 | 中文人妻av久久人妻18 | 蜜桃色一区二区三区 | 欧美日韩在线视频一区二区三区 | 性色AV无码久久一区二区三 | 久久久久久久亚洲av无码 | 手机看片福利在线 | sm久久捆绑调教精品一区 | 又黄又爽的视频在线观看 | 美女视频黄色 | 亚洲婷婷av| 婷婷伊人综合 | 绝顶高潮videos合集 | 色com| 成年人看的视频网站 | www国产91 | 中文字幕第12页 | 日日干日日射 | 91美女精品 | 在线观看欧美一区二区三区 | 欧美日韩国产大片 | 亚洲色图19p | 人人综合网 | 午夜快播| 欧美一级色图 | 中国特级毛片 | 99av视频 | 亚日韩 | 欧美一级不卡视频 | 在线观看免费黄视频 | 人人干人人草 | 波多野结衣一区二区三区高清av |