一、安装electron
npm install -g electron
二、使用
2-1:主进程的代码
//引入electron
var electron = require('electron')
//引用app
var app = electron.app
//窗口引用
var BrowserWindow = electron.BrowserWindow
//声明要打开的主窗口
var mainWindow = null
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 800,
height: 800,
webPreferences: {
nodeIntegration: true, //设置开启nodejs环境
contextIsolation: false //不加这句话就会报错
}
})
// 打开调试工具
mainWindow.webContents.openDevTools()
mainWindow.loadFile('index.html') //加载html静态页面
mainWindow.on('closed', () => {
mainWindow = null
})
})
electron报错:Uncaught TypeError: Cannot read property ‘BrowserWindow‘ of undefined
解决方案:
- list.js =》const btn 下面一行 更换为 const { BrowserWindow } = require('@electron/remote')
- main.js =》mainWindow.loadFile('list.html') 前加入下面两段代码
- require('@electron/remote/main').initialize()
- require('@electron/remote/main').enable(mainWindow.webContents)
- 此外还需npm install --save @electron/remote 下载@electron/remote
三、菜单的创建和绑定事件
创建main文件夹 =》 创建menu.js
//引入electron中的菜单
const { Menu } = require('electron')
//定义菜单中的模块
var template = [
{
label: '洗浴会所',
submenu: [
{
label: '拔罐',
// 绑定快捷键
accelerator: 'ctrl+n',
//点击事件弹出新窗口
click: function () {
var win = new BrowserWindow({
width: 500,
height: 500,
webPreferences: {
nodeIntegration: true, //设置开启nodejs环境
contextIsolation: false //不加这句话就会报错
}
})
win.loadFile('yellow.html')
win.on('closed', () => {
win = null
})
}
},
{ label: '桑拿' },
{ label: '精品spa' }]
},
{
label: '大浪淘沙洗浴中心',
submenu: [{ label: '牛奶玫瑰浴' }, { label: '爱情拍拍手' }]
}
]
// 引入模块
var m = Menu.buildFromTemplate(template)
// 模块创建到菜单中
Menu.setApplicationMenu(m)
右击事件:contextmenu
四、绑定右击菜单选项:
// 引入remote模块
var remote = require('@electron/remote')
//定义右击菜单中的模块
var rightTemplate = [
{
label: '复制',
// 绑定快捷键
accelerator: 'ctrl+c'
},
{
label: '粘贴',
// 绑定快捷键
accelerator: 'ctrl+v'
}
]
// 引入模块
var m = remote.Menu.buildFromTemplate(rightTemplate)
// 右击监听事件
window.addEventListener('contextmenu', function (e) {
// 阻止默认行为
e.preventDefault()
// 应用到右键
m.popup({
window: remote.getCurrentWindow()
})
})
五、通过链接打开浏览器
// 引入shell模块,通过谷歌浏览器进行打开,不是通过自身窗口打开
const { shell } = require('@electron/remote')
var aHref = document.querySelector('#aHref')
aHref.onclick = function (e) {
e.preventDefault()
var href = this.getAttribute('href')
shell.openExternal(href)
}
六、嵌入网页和打开子网页
- 嵌入网页
在主进程中 必须在主线程中使用 嵌入网页
var BrowserView = electron.BrowserView
var view = new BrowserView()
//嵌入网页到主窗口中部
mainWindow.setBrowserView(view)
// 设置大小
view.setBounds({ x: 0, y: 120, width: 600, height: 680 })
// 具体导入的网页
view.webContents.loadURL(
'https://blog.csdn.net/m0_52374678/article/details/124971212?spm=1001.2014.3001.5501'
)
七、子窗口向父窗口传递信息
子窗口:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3>我是弹出子窗口</h3>
<button id="popbth">向父窗口传递信息</button>
</body>
<script>
var popbth = document.querySelector('#popbth');
popbth.onclick = function (e) {
alert('111')
// 从子窗口向父窗口传递的信息
window.opener.postMessage('我是子窗口传递过来的')
}
</script>
</html>
父窗口:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo3</title>
</head>
<body>
<h1>
<a id="aHref" href="https://blog.csdn.net/m0_52374678/article/details/124971212?spm=1001.2014.3001.5501">我的博客</a>
</h1>
<button id="mybtn">打开子窗口</button>
<div id="mytext"></div>
</body>
<script>
// 引入shell模块,通过谷歌浏览器进行打开,不是通过自身窗口打开
const { shell } = require('electron')
var aHref = document.querySelector('#aHref')
aHref.onclick = function (e) {
e.preventDefault()
var href = this.getAttribute('href')
shell.openExternal(href)
}
var mybtn = document.querySelector('#mybtn')
mybtn.onclick = function () {
window.open('popup_page.html')
}
window.addEventListener('message', function (msg) {
let mytext = this.document.querySelector('#mytext')
mytext.innerHTML = JSON.stringify(msg.data)
})
</script>
</html>
八、选择文件对话框
- 打开文件选择对话框可以使用 dialog.showOpenDialog()
- 它有两个参数,一个是设置基本属性,另一个是回调函数,如果是异步可以使用
then
来实现。 - title : String (可选),对话框的标题
- defaultPath : String (可选),默认打开的路径
- buttonLabel : String (可选), 确认按钮的自定义标签,当为空时,将使用默认标签
- filters : 文件选择过滤器,定义后可以对文件扩展名进行筛选
- properties:打开文件的属性,比如打开文件还是打开文件夹,甚至是隐藏文件。
代码:
const { dialog } = require('@electron/remote');
var openBtn = document.getElementById('openBtn');
openBtn.onclick = function () {
dialog.showOpenDialog({
title: '请选择你喜欢的小姐姐照片',
defaultPath: '王紫秋.jpg',
filters: {
name: 'img',
extensions: ['jpg'],
},
buttonLabel: '打开小姐姐图片'
}).then(res => {
console.log(res);
let image = document.querySelector('#image');
image.setAttribute('src', res.filePaths[0])
}).catch(err => {
console.log(err);
})
}
九、保存文件对话框
- 打开文件选择对话框可以使用 dialog.showSaveDialog()
- 它有两个参数,一个是设置基本属性,另一个是回调函数,如果是异步可以使用
then
来实现。 - title : String (可选),对话框的标题
- defaultPath : String (可选),默认打开的路径
- buttonLabel : String (可选), 确认按钮的自定义标签,当为空时,将使用默认标签
- filters : 文件选择过滤器,定义后可以对文件扩展名进行筛选
- properties:打开文件的属性,比如打开文件还是打开文件夹,甚至是隐藏文件。
代码:
const fs = require('fs');
var saveBtn = document.querySelector('#saveBtn');
saveBtn.onclick = function () {
dialog.showSaveDialog({
title: '保存文件路径'
}).then(res => {
console.log(res);
fs.writeFileSync(res.filePath, '我是一个前端爱好者')
}).catch(err => {
console.log(err);
})
}
十、消息对话框操作
- 打开文件选择对话框可以使用 dialog.showMessageBox()
- 它有两个参数,一个是设置基本属性,另一个是回调函数,如果是异步可以使用
then
来实现。 - type :String类型,可以选,图标样式,有
none
、info
、error
、question
和warning
- title: String类型,弹出框的标题
- messsage : String 类型,必选 message box 的内容,这个是必须要写的
- buttons: 数组类型,在案例中我会详细的讲解,返回的是一个索引数值(下标)
代码:
var messageBtn = document.querySelector('#messageBtn');
messageBtn.onclick = function () {
dialog.showMessageBox({
title: '去不去洗脚中心',
type: 'none',
message: '是不是要跟槐哥去红袖招?',
buttons: ['我要去', '我不去', '我才不']
}).then(res => {
console.log(res);
})
}
十一、断网提醒功能制作
桌面客户端的程序都必备的一个功能是判断网络状态,这个其实可以用window.addEventListener
来进行时间监听。
其实这个是JavaScript的一种方式进行监听网络状态,监听的事件分别是online
和offline
。
- online : 如果链接上网络,就会触发该事件。
- offline : 如果突然断网了,就会触发该事件。
十二、底部消息通知的制作
Electron的消息通知是通过H5
的window.Notification
来实现的。
window.Notification的属性参数:
- title: 通知的标题,可以显示在通知栏上
- option: 消息通知的各种属性配置,以对象的形式进行配置。
代码:
<body>
<button id="notifyBtn">通知消息</button>
</body>
<script>
var notifyBtn = document.getElementById('notifyBtn');
var option = {
title:'小二,来订单了,出来接客了!',
body:'有大官人刚翻了你的牌子',
}
notifyBtn.onclick = function(){
new window.Notification(option.title,option)
}
</script>
十三、注册全局快捷键
globalShortcut
是主进程中的模块,而且注册的都是全局的快捷键,所以你尽量写在main.js
中。
然后先引入globalShortcut
,代码如下:
var globalShortcut = electron.globalShortcut
引入后,我们现在的需求是按快捷键ctrl+e
键后,打开百度。这时候使用globalShortcut.register
方法就可以实现,全部代码如下:
var mainWindow = null //声明要打开的主窗口
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: true, //设置开启nodejs环境
contextIsolation: false, //不加这句话就会报错
enableRemoteModule: true
}
})
// 注册全局快捷键
globalShortcut.register('ctrl+e', () => {
mainWindow.loadURL('https://baidu.com')
})
// 检测快捷键是否注册成功
let isRegister = globalShortcut.isRegistered('ctrl+e') ? 'Register success' : 'Register fail'
console.log(isRegister, '===========')
// 打开调试工具
mainWindow.webContents.openDevTools()
require('@electron/remote/main').initialize()
require('@electron/remote/main').enable(mainWindow.webContents)
require('./main/menu')
mainWindow.loadFile('demo6.html') //加载html静态页面
//监听关闭事件,把主窗口设置为null
mainWindow.on('closed', () => {
mainWindow = null
})
注销快捷键:
因为我们注册的是全局的快捷键,所以当我们关闭软件或者窗口时,记得一定要注销我们的快捷键。防止关闭后打开其他软件和他们的快捷键冲突。
app.on('will-quit',function(){
//注销全局快捷键的监听
globalShortcut.unregister('ctrl+e')
globalShortcut.unregisterAll()
})
十四、剪切模板的使用
在开发中我们经常会遇到给用户一个激活码,然后让用户复制粘贴的情况,这时候就需要用到clipboard
模块,也就是我们的剪贴板模块。
代码:
<body>
<div>
激活码:<span id="code">jspangcom1234234242</span> <button id="btn">复制激活码</button>
</div>
</body>
<script>
// 引入 clipboard 模块
const {clipboard} = require('electron')
// 获取dom元素
const code = document.getElementById('code')
const btn = document.getElementById('btn')
btn.onclick = function(){
// 复制这个激活码
clipboard.writeText(code.innerHTML)
alert('复制成功')
}
</script>