electron 筆記大全(未整理完)

electron大部分常用的API都在這了

主進程核心代碼:

    const { app, BrowserWindow } = require('electron)
    app.on('ready', () => {
        const mainWindow = new BrowserWindow({
            width: ,
            height: ,
            frame: false,
            show: false,
            webPreferences: { // 網頁功能設置
                nodeIntegration: true, // 集成Node
                webviewTag: true, // 啓用webview標籤
            }
        })
        mainWindow.loadURL('/index.html')
        mainWindow.on('ready-to-show', () => {
            mainWindow.show()
            mainWindow.webContents.openDevTools()
        })
        mainWindow.on('closed', () => {
            mainWindow = null
        })
        mainWindow.on('resize', () => {
            mainWindow.reload()
        })
    })
    app.on('window-all-closed', () => {
        app.quit()
    })

窗口透明

	mainWindow = new BrowserWindow({ transparent: true }) // 前提是窗口的CSS中沒設背景色
	// 如果需要完全透明,讓鼠標可以透過窗口對桌面點擊,需要以下代碼
	mainWindow.setIgnoreMouseEvents(true)

app常用事件(生命週期):

使用:

	 app.on("eventName",() => { } )
  • ready: 當electron完成初始化時被觸發
  • window-all-closed: 所有窗口被關閉
  • before-quit: 在應用程序開始關閉窗口之前觸發
  • will-quit: 當所有窗口都已關閉並且應用程序將退出時發出
  • quit: 在應用程序退出時發出

webContents常用事件:

使用:

	mainWindow.webContents.on("eventName",() => { } )
  • dom-ready: 一個框架中的文本加載完成後觸發該事件
  • did-finish-load: 導航完成時觸發,即選項卡的旋轉器將停止旋轉

進程對象(node提供的函數):

  • getCPUUsage: CPU佔用率
  • env: 環境變量
  • arch: CPU信息(x64/x32)
  • platform: 操作系統

使渲染進程的js支持node:

	new BrowserWindow({ webPreferences: { nodeIntegration: true } })

使webview生效:

	new BrowserWindow({ webPreferences: { webviewTag: true } })

webview標籤(官方不推薦使用)(是單獨的進程):

使用:

  	<webview src="www.baidu.com" nodeintegration preload="xxx.js" />
  • 使web支持node:
    nodeintegration 屬性使嵌入的web支持node,但是不安全
  • 賦予js:
    1. preload 屬性能讓web多賦予一個js文件
    2.
     document.querySelector('webview').executeJavaScript(`
          console.log('hello world')
     `)
    
  • 賦予css:
     document.querySelector('webview').insertCSS(`
          *{
              margin: 0;
              padding: 0;
          }
      `)
    
  • 自動打開控制檯:
    document.querySelector('webview').openDevTools()
    

父子窗口間通信

  • 以原窗口打開子窗口:
     window.open(url,frameName)
    
  • 發送方:
     window.openner.postMessage(message,target)  // 無target則爲所有子窗口
    
  • 接收方:
     window.addEventListener('message',(e) => {
        console.log(e)
     })
    
  • 關閉子窗口:
      let child = window.open(url)
      child.close()
    

///////////////////////////////////////////////////以下未整理////////////////////////////////////////////////////

BrowserWindow的參數:
new BrowserWindow({
width: 500px,
height: 500px,
x: 0, // x,y缺省時默認居中
y: 0,
frame: false, // 去掉狀態欄
background: ‘#000’, // 設置背景色(不包括狀態欄部分)
parent: xxx, // 指定父窗口
modal: true, // 設爲模態窗口(子窗口能操作,父窗口不能操作)(不常用),
webPreferences: { // 網頁功能設置
nodeIntegration: true, // 集成Node
webviewTag: true, // 啓用webview標籤
}
})

BrowserView:
類似於webview
const view = new BrowserView()
view.setBounds({
x: 10,
y: 10,
width: 300,
height: 200
})
view.webContents.loadURL(‘http://www.baidu.com’)
mainWindow.setBrowserView(view)
view.destroy() // 摧毀

對話框dialog:
主線程獲取dialog:
const { dialog } = require('electron)
渲染進程獲取dislog:
const { dialog } = require(‘electron).remote
打開文件對話框:
showOpenDialogSync 或showOpenDialog
dialog.showOpenDialogSync({
title: ‘請選擇文件’,
buttonLabel: ‘走你’, // 默認爲’確定’
filters: [
{ name: ‘JS File Type’, extensions: [ ‘js’ ] },
{ name: ‘Image File Type’, extensions: [ ‘jpg’, ‘png’, ‘gif’ ] }
]
})
保存文件對話框:
dialog.showSaveDialog({
title: ‘請保存你的文件’,
buttonLabel: ‘保存’,
filters: [
{ name: ‘JS File’, extensions: [ ‘js’ ] },
{ name: ‘Image File’, extensions: [ ‘jpg’, ‘png’, ‘gif’ ] }
]
}, filename => {
fs.writeFileSync(filename, ‘這裏是文件內容’)
})
消息對話框:
dialog.showMessageBox({
type: ‘warning’, // ‘none’/‘info’/‘error’/‘question’/‘warning’,
title: ‘請三思’,
message: ‘是否真的刪除該信息’,
buttons: [‘ok’,‘cancel’], // 有些系統不一定生效
}, res => {
console.log('你的選擇爲: ', res) // 0爲左邊,1爲右邊
})

系統快捷鍵:
主進程獲取:
const { globalShortcut } = require(‘electron’)
渲染進程獲取:
const { remote } = require('electron)
remote.globalShortcut
註冊:
globalShortcut.register(‘CommandOrControl+X’, () => {
console.log(‘hhh’)
})
查看是否已被註冊:
globalShortcut.risRgistered(‘CommandOrControl+X’)
刪除:
globalShortcut.unregister(‘CommandOrControl+X’
刪除所有:
globalShortcut.unregisterAll()

主進程與渲染進程的異步通信:

  • 在主進程中:
    • 被動通信:
          const { ipcMain } = require('electron)
          ipcMain.on('asyncchronous-message', (event,arg) => {
              console.log(arg) // prints "ping"
              event.reply('asynchoronous-reply','pong') // 對應send
          })
          ipcMain.on('synchronous-message', (event,arg) => {
              console.log(arg) // prints "ping"
              event.returnValue = "pong" // 對應sendSync
          })
          ```
      
    • 主動通信:
          mainWindow.webContents.send('asyncchronous-reply','hhh')
      
  • 在渲染進程中:
        const { ipcRenderer } = require('electron)
        console.log( ipcRenderer.sendSync('synchronuos-message','ping') ) // prints "pong"
        ipcRenderer.on('asyncchronous-reply', (event,arg) => {
            console.log(arg) // prints "hhh" & "pong"
        })
        ipcRenderer.send('asyncchronous-message','ping')
        ```
    
    

菜單menu:
主進程的菜單(不常用):
const { Menu } = require(‘electron’)
const template = [
{ label: “first” },
{ type: “separator” // 分割線 }
]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu) // 設置狀態欄主菜單
menu.popup() // 彈出右鍵的菜單
渲染進程的菜單:
const { remote } = require(‘electron’)
const { Menu,MenuItem } = remote
const template = [ // 數組的每個元素都是MenuItem,一下有兩種寫法
{
label: “first”,
click: () => {
console.log(‘click-ok’)
}
},
{
label: “國籍”,
submenu: [
{ label: “中國” },
{ label: “美國” }
]
},
{
label: “英文”,
type: “checkbox”, // type默認缺省爲normal
checked: true // 默認icon爲✔
},
{
label: “中文”,
type: “checkbox”,
checked: true
},
new MenuItem({
{
label: “日文”,
type: “checkbox”,
checked: true
},
})
]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu) // 設置狀態欄主菜單
menu.popup() // 彈出右鍵的菜單

網絡模式:
electron使用的是Chromium的原生網絡庫發出HTTP/HTTPS請求,優點是不依賴electron,缺點是代碼量龐大,不利於開發
const { net } = require(‘electron’) // 渲染進程通過remote獲取
const request = net.request(‘https://www.baidu.com’)
request.on(‘response’, (response) => {
console.log( response.statusCode, JSON.stringify(response.headers) )
let str
response.on(“data”, (chunk) => {
str += chunk.toString()
})
response.on(“end”, () => {
console.log(str)
})
})
request.end()

可拖拽區(一般設爲狀態欄):
先frame: false禁掉默認狀態欄,否則無效
在可拖拽區域設置樣式 -webkit-app-region: drag;
狀態欄設置後按鈕會失效
按鈕設置樣式 -webkit-app-region: no-drag

開發者工具:
自動打開開發者工具進行調試
mainWindow.webContents.openDevTools()

窗口失焦聚焦:
render.js中: window.onblur = () => { } // 失焦

main.js中: window.on(‘blur’, () => {
進程間通信
})

自制狀態欄:
失焦變暗
窗口關閉: window.close() // 關閉窗口並退出 或 window.hide() // 隱藏窗口而不退出
最大化 / 還原 / 最小化:
進程通信 + mainWindow.maximize() / setSize(寬度,高度) / minimize()
雙擊 最大化 / 還原

系統托盤:
const { app, Menu, Tray } = require(‘electron’)
let tray = null
app.on(‘ready’, () => {
tray = new Tray(’/path/to/my/icon’)
const contextMenu = Menu.buildFromTemplate([
{ label: ‘Item1’ },
{ label: ‘quit’, click: ()=> app.quit() }
])
tray.setToolTip(‘this is my application’)
tray.setContextMenu(contextMenu)
})
點擊事件:
tray.on(‘click’, () => { })

托盤氣球通知:
這裏的tray看 | 系統托盤 |
tray.displayBalloon({
title: ‘警告’,
content: ‘我最帥’,
iconType: ‘warning’, // 或 icon: ‘xxx.jpg’ (只支持win10)
})
退出:
tray.removeBalloon()

接觸網絡安全:
桌面打開想文件跨域的話,得解除安全
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
webSecurity: false,
}
})

使用項目打開文件:

	//主線程代碼
	global.fileToOpen = "";
	app.on('open-file', (event, path) => {
    // 當用戶想要在應用中打開一個文件時發出。 
    // 事件通常在應用已經打開,並且系統要再次使用該應用打開文件時發出。 
    // 也會在一個文件被拖到 dock 並且還沒有運行的時候發出。 
   		event.preventDefault()
	    fileToOpen = path;
	    //win是打開的窗口,如果程序未啓動則不會觸發
	    //窗口打開後可通過渲染進程代碼global來獲取路徑
	    if(win){
	        win.webContents.send("activateThenOpenFile",fileToOpen)
	    }
	});
	//渲染進程代碼(路徑得到就ok了)
	let currentFile = this.$electronRemote.getGlobal('fileToOpen') || null;

原文鏈接:https://blog.csdn.net/WuQingLaoXingXing/article/details/105841278

配置數據 或 臨時數據 的存儲:
主進程app.getPath(name)

name:
    exe
    module
    home
    userData 儲存應用程序配置的文件 (應用第一次用時時需要的數據)
    appData 當前用戶的應用數據文件夾 (應用第一次使用後,經用戶的使用,額外存儲的數據) , 返回值默認是 appData 文件夾附加應用的名稱
    desktop
    documents
    downloads
    music
    pictures
    videos
    logs
    pepperFlashSystemPlugin

重啓:
先 app.relaunch()
後 app.exit(0) 或 app.quit()

應用的路徑: app.getAppPath()

設置應用名稱:
package.json中修改productName (首字母大寫)
app.setName(‘JulnMusic’) 已過時

存儲數據:
- window.localStorage 不推薦
- electron-store模塊 (原理是儲存到本地的AppData, 存儲的目錄是C:\Users\mi\AppData\Roaming\項目名\config.json)

安裝: npm i electron-store -S
使用:
const Store = require(‘electron-store’)
const store = new Store()
// 或
const store = new Store({
foo: { // key
type: ‘number’,
maximum: 100, // 限制
minimum: 1,
default: 50 // 默認值
},
bar: {
type: ‘string’,
format: ‘url’
}
})
store.set(‘unicorn’, ‘🦄’)
console.log(store.get(‘unicorn’)) // 🦄
store.set(‘foo.bar’, true)
console.log(store.get(‘foo’)) // { bar:true }
store.delete(‘unicorn’)
console.log(store.get(‘unicorn’)) // undefined

electron6的音樂資源不能緩存的問題:

  1. https://www.cnblogs.com/axes/p/7151759.html

  2. https://blog.csdn.net/qq_39050445/article/details/105066444

窗口頂置:

窗口頂置 是 相對於電腦所有應用的

	mainWindow.setAlwaysOnTop()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章