1. Create a new folder to store the client
mkdir my-electron-app && cd my-electron-app//客户端存放地址
npm init//初始化
2. Install Electron
npm install --save-dev electron
3. Create a new app folder
1. An insignificant step, in order to ensure a clear directory structure
2. Create a new index.js file under this folder, and paste the following code into it
// ./app/index.js
//采用javascript严格模式
'use strict';
const {app,Menu,protocol,BrowserWindow, MenuItem } =require('electron');
var mainWindow = null;
protocol.registerSchemesAsPrivileged([
{//跨域等问题解决 打开摄像头等
scheme: 'http',
privileges: {
bypassCSP: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true
}
}
]);
// 当所有窗口都关闭的时候退出应用
app.on('window-all-closed', function () {
if (process.platform != 'darwin') {
app.quit();
}
});
// 初始化并准备创建浏览器窗口
app.on('ready', function () {
//隐藏菜单
Menu.setApplicationMenu(null);
// 创建浏览器窗口.
mainWindow = new BrowserWindow({show:false,webPreferences: {
nativeWindowOpen: true
}});
mainWindow.maximize()
mainWindow.show();
//mainWindow.webContents.openDevTools();
// 载入应用的 index.html
mainWindow.loadURL("http://127.0.0.1:8080");
// 打开开发工具
// mainWindow.openDevTools();
// 定义菜单
const menu = new Menu();
menu.append(new MenuItem({label: '复制', role: 'copy'}));
menu.append(new MenuItem({label: '粘贴', role: 'paste'}));
menu.append(new MenuItem({label: '刷新', role: 'reload'}));
//menu.append(new MenuItem({label: '全选', role: 'selectall'}));
//menu.append(new MenuItem({label: '剪切', role: 'cut'}));
//menu.append(new MenuItem({label: '删除', role: 'delete'}));
// menu.append(new MenuItem({label: '取消', role: 'undo'}));
//menu.append(new MenuItem({label: '重置', role: 'redo'}));
mainWindow.webContents.on('context-menu', (e, params) => {
menu.popup({window: mainWindow, x: params.x, y: params.y});
})
// 窗口关闭时触发
mainWindow.on('closed', function () {
// 想要取消窗口对象的引用,如果你的应用支持多窗口,
// 通常你需要将所有的窗口对象存储到一个数组中,
// 在这个时候你应该删除相应的元素
mainWindow = null;
});
});
3. Replace the above mainWindow.loadURL("http://127.0.0.1:8080"); with the address of your server
4. Transform package.json
According to your package.json, change it to be similar to mine, change main (if there is no new app folder above), and scripts
{
"name": "lsy",
"version": "1.0.0",
"description": "",
"main": "app/index.js",
"scripts": {
"start": "electron .",
"package": "electron-packager . lsy --platform=win32 --arch=x64 --icon=computer.ico --out=./out --app-version=0.0.1 --overwrite --ignore=node_modules"
},
"author": "lsy",
"license": "ISC",
"devDependencies": {
"electron": "^18.1.0"
}
}
5. Add client icon
Add an icon named after computer to the project folder
6. Pack
npm run package
7. Open the client
Find this exe file and run it