先來講一個 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>
複製代碼