electron-vue通过自定义协议唤起,并且在协议后面加参数传递到程序中(协议唤起不区分浏览器)。需求为通过链接唤起程序并区分进入不同页面(本文只测试Windows环境)。
一、项目背景
先有Vue项目,后安装electron并通过electron-builder打包,安装完后会自动生成background.js并在package.json中添加入口,简单看下关键配置不做过多解释:
二、注册协议(注册协议和接收参数都在background.js中)
在创建窗口createWindow方法中添加如下代码,主要是setAsDefaultProtocolClient,本文唤起方法myapp://startapp?userid=111§ionid=222&q=123 ,参数自定义加减都可,startapp如果去掉,接收参数会有所不同但是不影响唤起程序(去掉后感觉有点奇怪)
const PROTOCOL = 'myapp';//协议名称自定义
const args = [];//介绍说是win需要的参数
if (!app.isPackaged) {
args.push(path.resolve(process.argv[1]));
}
args.push('--');
app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, args);
三、接收协议传递参数(注册协议和接收参数都在background.js中)
网上看了很多方法几乎都是通过app.on('second-instance',...)和app.on('open-url',...)去获取参数,折腾了好久放弃了,如果有小伙伴成功了欢迎留言。
进入正题,思路:在app.on('ready',...)方法中调用createWindow时传参数,这样就可以在进入页面时把参数通过win.loadURL拼接到URL上。贴上两段关键代码,文章结尾会附上background.js完整代码。
app.on('ready', async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installExtension(VUEJS_DEVTOOLS)
} catch (e) {
console.error('Vue Devtools failed to install:', e.toString())
}
}
let par;
try{
par=process.argv[2]
}catch(e){
console.log(e);
}
createWindow(par)
})
async function createWindow(par) {
// Create the browser window.
win = new BrowserWindow({
width: 1000,
height: 600,
webPreferences: {
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
}
})
// 打开开发工具
win.webContents.openDevTools()
//注册协议
app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, args);
if (process.env.WEBPACK_DEV_SERVER_URL) {
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) {
win.webContents.openDevTools()
}
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html?par='+par)//参数名称自定义,此处app:只是内部调用和唤起协议无关
}
}
四、Vue接收参数
Vue接收参数很简单,在main入口一般都有路由守卫,直接打印to.query方法查看即可
router.beforeEach((to, from, next) => {
console.log(to.query);//打印出所有协议传递参数
console.log((to.query.par));
if(to.query.par){
console.log(to.query.par.split('=')[1]);//第一个参数会和协议一起需要切割下
}
})
五、background.js所有代码
import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
const path = require('path');
const gotTheLock = app.requestSingleInstanceLock();
const PROTOCOL = 'myapp';
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } }
])
let win;
const args = [];
if (!app.isPackaged) {
args.push(path.resolve(process.argv[1]));
}
args.push('--');
async function createWindow(par) {
// Create the browser window.
win = new BrowserWindow({
width: 1000,
height: 600,
webPreferences: {
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
}
})
// 打开开发工具
win.webContents.openDevTools()
//注册协议
app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, args);
if (process.env.WEBPACK_DEV_SERVER_URL) {
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) {
win.webContents.openDevTools()
}
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html?par='+par)
}
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installExtension(VUEJS_DEVTOOLS)
} catch (e) {
console.error('Vue Devtools failed to install:', e.toString())
}
}
let par;
try{
par=process.argv[2]
}catch(e){
console.log(e);
}
createWindow(par)
})
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === 'win32') {
process.on('message', (data) => {
if (data === 'graceful-exit') {
app.quit()
}
})
} else {
process.on('SIGTERM', () => {
app.quit()
})
}
}
if (!gotTheLock) {
app.quit();
}