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的音乐资源不能缓存的问题:
窗口顶置:
窗口顶置 是 相对于电脑所有应用的
mainWindow.setAlwaysOnTop()