先来讲一个 vue-electron 的报错
C:\Users\user\Desktop\dome\my-im\node_modules\_electron-localshortcut@3.2.0@electron-localshortcut\index.js:20
} catch {
SyntaxError: Unexpected token {
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:606:28)
at Object.Module._extensions..js (module.js:653:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:504:12)
at Function.Module._load (module.js:496:3)
at Module.require (module.js:586:17)
at require (internal/module.js:11:18)
at eval (webpack:
复制代码
前言注意
<script> this.$electron.shell.openExternal(link) </script>
<style> @import url('https://www.baidu.com/index.css') </style>
复制代码
全局安装
npm install -g electron
npm install -g electron-forge
复制代码
建立 项目
electron-forge init my-app
复制代码
运行 项目
npm start
复制代码
结合vue建立项目
vue cerate app
vue add vue-cli-plugin-electron-builder
yarn electron:serve
yarn electron:build
复制代码
主进程
import { app, BrowserWindow, Menu} from 'electron'
if (process.env.NODE_ENV !== 'development') {
global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
let mainWindow
const winURL = process.env.NODE_ENV === 'development'
? `http://localhost:9080`
: `file://${__dirname}/index.html`
function createWindow () {
mainWindow = new BrowserWindow({
height: 763,
useContentSize: true,
fullscreenable: true,
width: 1200,
frame: true,
center: true ,
title: '云笔记',
titleBarStyle: 'hidden',
webPreferences: {
backgroundThrottling: false
}
})
mainWindow.loadURL(winURL)
mainWindow.on('closed', () => {
mainWindow = null
})
mainWindow.webContents.openDevTools()
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
复制代码
小试牛刀——读取本地文件
const fs = require('fs')
export default {
methods:{
btn:function(){
fs.readFile('package.json',(err,data)=>{
console.log(data)
this.$refs.texts.innerHTML=data
})
}
}
}
复制代码
开启初始化的调试模式
mainWindow.webContents.openDevTools()
复制代码
拖拽
<div v-on:drop.prevent="drop" v-on:dragenter="dragenter" v-on:dragover="dragenter" v-on:dragleave="dragenter" class="box" id="box" >
</div>
<script> const fs = require('fs') export default { methods:{ dragenter:function(){ return false; }, drop:function(e){ console.log(e) } } } </script>
复制代码
隐藏菜单
mainWindow.setMenu(null)
复制代码
去掉顶部 最大化、最下化
mainWindow = new BrowserWindow({
height: 763,
useContentSize: true,
fullscreen: false,
width: 1200,
frame: false,
center: true ,
title: '云笔记',
titleBarStyle: 'hidden',
webPreferences: {
backgroundThrottling: false
}
})
复制代码
能够拖动 的CSS
.box{
webkit-app-region: drag
}
复制代码
自定义 最小化、最大化、关闭
min:function(){
this.$electron.ipcRenderer.send('window-min')
},
max:function(){
this.$electron.ipcRenderer.send('window-max')
},
close:function(){
this.$electron.ipcRenderer.send('window-close')
}
复制代码
注册全局快捷键
const {app,globalShortcut,BrowserWindow} = require('electron')
let win=BrowserWindow.getFocusedWindow();
app.on('ready',function(){
globalShortcut.register('ctrl+e',function(){
console.log('123')
})
let glos=globalShortcut.isRegistered('ctrl+e')
console.log(glos)
})
app.on('will-quit',function(){
globalShortcut.unregister('ctrl+e')
})
复制代码
注册剪切板
clipboard.writeText('机器码')
复制代码
webview
<webview src='http://www.baidu.com'></webview>
复制代码
通知 window.Notification
let options={
title: '通知',
body: '你有新短消息,请注意查收',
}
let defaults=window.Notification.permission
console.log(defaults)
var myNotification= new Notification(options.title,options);
myNotification.onclick=function(){
console.log('点击了')
}
let bons =document.getElementById('bons')
bons.onclick=function(){
console.log('123')
let myNotifications= new window.Notification(options.title,options);
console.log(myNotifications)
myNotifications.onclick=function(){
console.log('点击了')
}
}
window.addEventListener('online',function(){
console.log('有网络')
})
window.addEventListener("offline",function(){
console.log('网络断开')
})
复制代码
实践
<body>
<button id="btn">按钮</button>
</body>
<script> let btn=document.getElementById('btn') let options={ title: '通知', body: '你有新短消息,请注意查收' } btn.onclick=function(){ let notifications=null if (!window.Notification) { alert("浏览器不支持通知!"); } if(window.Notification.permission != 'granted'){ window.Notification.requestPermission(function(stauts){ console.log(stauts) if(stauts=='granted'){ notifications=new window.Notification(options.title,options); }else{ alert('您为容许开启消息通知,将接收不到 本站的消息推送') } }) } notifications=new window.Notification(options.title,options); notifications.onclose=function(){ } notifications.onshow=function(){ } } </script>
复制代码
dialog 窗口提示和打开、保存文件
<template>
<div class="notebook">
<button v-on:click="btn">点击l</button>
<webview id="webs" src='http://www.bbaidu.com'></webview>
<button v-on:click="btna">错误提示</button>
<button v-on:click="btnb">选择提示</button>
<button v-on:click="btnc">打开文件</button>
<button v-on:click="btnd">另存为</button>
</div>
</template>
<script> const {shell,ipcRenderer,remote} = require('electron') export default { methods:{ btn:function(){ console.log('123') shell.openExternal('https://www.baidu.com/') }, btna:function(){ remote.dialog.showErrorBox('错误提示','错误了') }, btnb:function(){ remote.dialog.showMessageBox({ title: '提示信息', message: '内容', type: 'info', buttons: ['肯定','取消'] },function(index){ console.log(index) }) }, btnc:function(){ remote.dialog.showOpenDialog({ properties:['openFile'] },function(data){ console.log(data) }) }, btnd:function(){ remote.dialog.showSaveDialog({ title: 'save file', defaultPath: 'abs.gif', filters:[ { name: 'Images', extensions:['jpg','png','gif'] }, { name: 'Movies', extensions:['mkv','avi','mp4'] }, { name: 'Custom File Type', extensions:['as'] }, { name: 'All Files', extensions:['*'] } ] },function(data){ console.log(data) }) } }, mounted:function(){ console.log('hhahha') ipcRenderer.on('webs',function(event,data){ let webs=document.getElementById('webs') webs.src=data }) } } </script>
复制代码
shell模块
//在外部浏览器打开链接地址,也能够打开本地目录
<template>
<!-- 云笔记 主页 -->
<div class="notebook">
<button v-on:click="btn">点击l</button>
</div>
</template>
<script>
//
const {shell} = require('electron')
export default {
methods:{
btn:function(){
console.log('123') //打开外部浏览器
this.$electron.shell.openExternal('https://www.baidu.com/')
}
}
}
</script>
复制代码
在页面嵌套页面,相似iframe
<webview src='https://www.baidu.com/'></webview>
复制代码
主进程:ipcMain,渲染进程:ipcRenderer 通信
var win= BrowserWindow.getFocusedWindow()
win.webContents.send('opens',data)
复制代码
渲染进程 向主进程 发送数据
// 渲染进程
<template>
<div class="notebook">
<button v-on:click="btn">点击</button>
</div>
</template>
<script> const fs = require('fs') const {ipcRenderer} = require('electron') export default { methods:{ btn:function(){ ipcRenderer.send('sendM','this is home') } } } </script>
<scripr>
// 主进程
import { ipcMain} from 'electron'
ipcMain.on('sendM',function(event,data){
console.log(data)
})
/* 在下面生命周期中执行
* 当electron完成初始化后触发
* app.on('ready', createWindow)
*/
</scripr>
复制代码
渲染进程 向主进程 发送数据,并返回处理结果给渲染进程
<template>
<div class="notebook">
<button v-on:click="btn">点击</button>
</div>
</template>
<script> const fs = require('fs') const {ipcRenderer} = require('electron') export default { methods:{ btn:function(){ ipcRenderer.send('sendM','this is home') } }, mounted:function(){ ipcRenderer.on('replay',(event,data)=>{ console.log(data) }) } } </script>
<script> import { ipcMain} from 'electron' ipcMain.on('sendM',function(event,data){ event.sender.send('replay','ok hello') }) </script>
复制代码
同步广播
<template>
<div class="notebook">
<button v-on:click="btn">点击</button>
</div>
</template>
<script> const fs = require('fs') const {ipcRenderer} = require('electron') export default { methods:{ btn:function(){ let src=ipcRenderer.sendSync('sendM','this is home') console.log(src) } }, mounted:function(){ } } </script>
<script> import { ipcMain} from 'electron' ipcMain.on('sendM',function(event,data){ event.returnValue='this is sync main' }) </script>
复制代码
实例
import { ipcMain, BrowserWindow} from 'electron'
var win;
ipcMain.on('sendM',function(event,data){
win= new BrowserWindow({
width:300,
height: 400
})
win.loadURL('https://www.baidu.com/')
win.webContents.openDevTools()
win.on('closed',()=>{
win=null
})
})
复制代码
渲染进程 与 渲染进程 单项通信
import { ipcMain, BrowserWindow} from 'electron'
var win;
ipcMain.on('sendM',function(event,data){
win= new BrowserWindow({
width:300,
height: 400
})
win.loadURL('https://www.baidu.com/')
win.webContents.openDevTools()
win.webContents.on('did-finish-load',function(){
win.webContents.send('Load','ha ha hehe')
})
win.on('closed',()=>{
win=null
})
})
复制代码
ipcRenderer.on('Load',function(event,data){
console.log(data)
})
复制代码
渲染进程 与渲染 进程 相互通信
ipcMain.on('sendM',function(event,data){
var winId = BrowserWindow.getFocusedWindow().id
win= new BrowserWindow({
width:300,
height: 400
})
win.loadURL('https://www.baidu.com/')
win.webContents.openDevTools()
win.webContents.on('did-finish-load',function(){
win.webContents.send('Load','ha ha hehe',winId)
})
win.on('closed',()=>{
win=null
})
})
复制代码
const fs = require('fs')
const {ipcRenderer} = require('electron')
const BrowserWindow =require('electron').remote.BrowserWindow
export default {
mounted:function(evemt,data,winId){
let firstWinid= BrowserWindow.fromId(winId)
firstWinid.webContents.send('toIndex', 'this is news');
}
}
复制代码
Tray 模块
let {app,Menu,Tray,shell,ipcMain,BrowserWindow} = require('electron');
var iconTray=new Tray(path.join(__dirname,'../static/imgs/app2.png'));
var tpl=[
{
label: '设置',
click:function(){
console.log('123')
}
},
{
label: '退出',
click:function(){
console.log('123')
}
}
]
let rightIcon=Menu.buildFromTemplate(tpl)
iconTray.setContextMenu(rightIcon)
iconTray.setToolTip('云应用')
let win=BrowserWindow.getFocusedWindow();
win.on('close',(e)=>{
if(!win.isFocused()){
win=null
}else{
e.preventDefault();
win.hide();
}
})
iconTray.on('double-click',function(){
win.show()
})
复制代码
在渲染进程 打开 另一个 渲染进程,remote模块
let BrowserWindow = require('electron').remote.BrowserWindow
let win=null
win=new BrowserWindow({
height: 763,
useContentSize: true,
fullscreen: true,
width: 1200,
frame: true,
center: true ,
title: '云笔记',
titleBarStyle: 'hidden',
autoHideMenuBar : true,
webPreferences: {
backgroundThrottling: false
}
})
let winURL=path.join("file:",__dirname,'news.html')
mainWindow.loadURL(winURL)
mainWindow.on('closed'.()=>{
win=null
})
复制代码
自定义 顶部菜单 menu 模块,在主进程
menus.js
import { Menu} from 'electron'
let template=[
{
label: '文件',
submenu:[
{
label: '新建窗口',
click:function(){
console.log('新建窗口')
},
accelerator: 'ctrl+n'
},
{
type: 'separator'
},
{
label: '打开文件',
accelerator: 'ctrl+x',
click:()=>{
console.log('打开文件')
}
}
]
},
{
label: '编辑',
submenu:[
{
role: 'cut',
label: '剪切'
},
{
rele: 'copy',
label: '复制'
}
]
}
]
let m= Menu.buildFromTemplate(template)
Menu.setApplicationMenu(m)
app.on('ready', {
require('./menu')
})
复制代码
自定义 顶部菜单 menu模块,在渲染进程中
const {Menu} = require('electron').remote;
let template=[
{
label: '文件',
submenu:[
{
label: '新建窗口',
click:function(){
console.log('新建窗口')
},
accelerator: 'ctrl+n'
},
{
type: 'separator'
},
{
label: '打开文件',
accelerator: 'ctrl+x',
click:()=>{
console.log('打开文件')
}
}
]
},
{
label: '编辑',
submenu:[
{
role: 'cut',
label: '剪切'
},
{
rele: 'copy',
label: '复制'
}
]
}
]
let m= Menu.buildFromTemplate(template)
Menu.setApplicationMenu(m)
复制代码
渲染进程的 右键菜单
const remote= require('electron').remote;
const Menu = remote.Menu
let template=[
{
label: '文件',
submenu:[
{
label: '新建窗口',
click:function(){
console.log('新建窗口')
},
accelerator: 'ctrl+n'
},
{
type: 'separator'
},
{
label: '打开文件',
accelerator: 'ctrl+x',
click:()=>{
console.log('打开文件')
}
}
]
},
{
label: '编辑',
submenu:[
{
role: 'cut',
label: '剪切'
},
{
rele: 'copy',
label: '复制'
}
]
}
]
let m= Menu.buildFromTemplate(template)
Menu.setApplicationMenu(m)
window.addEventListener('contextmenu',function(e){
e.preventDefault()
m.popup({
window:remote.getCurrentWindow()
})
},false)
复制代码
主进程 右键菜单
window.addEventListener('contextmenu',(e)=>{
<!--this.$electron.ipcRenderder.emit('contextmenu')-->
this.$electron.ipcRenderer.send('contextmenu');
},false)
const { Menu, ipcMain, BrowserWindow } = require('electron');
const contextMenuTemplate=[
{
label: '复制',
role: 'copy'
},
{
label: '粘贴',
role: 'paste'
},
{
type: "separstor"
},
{
label: '其余功能',
click:()=>{
console.log('自定义功能')
}
}
]
const contextMenu = Menu.buildFromTemplate(contextMenuTemplate)
ipcMain.on('contextmenu',function(){
contextMenu.popup(BrowserWindow.getFocusedWindow())
})
require('./menu.js')
复制代码
点击菜单栏 在 软件内部 或者 外部默认浏览器 打开网页
import { Menu,shell,BrowserWindow} from 'electron'
let template=[
{
label: '加载网页',
submenu: [
{
label: '优酷',
click: function(){
shell.openExternal('http://www.baidu.com')
}
},
{
type: 'separator'
},
{
label: '百度',
click: function(){
let win= BrowserWindow.getFocusedWindow();
win.webContents.send('webs','http://www.youku.com')
}
}
]
},
{
label: '帮助',
submenu: [
{
label:'关于咱们',
click:function(){
}
}
]
}
]
复制代码
<template>
<div class="notebook">
<button v-on:click="btn">点击l</button>
<webview id="webs" src='http://www.baidu.com'></webview>
</div>
</template>
<script> const {shell,ipcRenderer} = require('electron') export default { methods:{ btn:function(){ console.log('123') shell.openExternal('https://www.baidu.com/') } }, mounted:function(){ ipcRenderer.on('webs',function(event,data){ let webs=document.getElementById('webs') webs.src=data }) } } </script>
复制代码