一、创建项目
1. 新建项目文件夹:electron-demo
2. npm init -y
3. npm install electron --save-dev
4. 项目根目录下新建文件 ==》 index.js
5. 修改package.json中的scripts, 添加启动命令 "start": "electron ."
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron ."
},
二、index.js 文件
const electron = require('electron')
console.log(electron)
const { app, BrowserWindow, Menu, ipcMain } = electron
let win = null;
app.on('ready',()=>{
console.log( 'ready' )
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
win.loadFile('index.html')
const mainMenu = Menu.buildFromTemplate( menuTemplate )
Menu.setApplicationMenu( mainMenu )
})
const menuTemplate = [
{
label:'文件',
submenu:[
{
label:'添加',
click:()=>{
createAddWindow()
}
},
{ label:'编辑' },
{ label:'查看' },
]
},
{label:'文档'},
{
label:'退出',
click: ()=>{
app.quit();
}
},
{
label:'开发工具',
submenu:[
{
label:'打开/关闭',
accelerator: 'F12',
click: (item, focusedWindow) => {
focusedWindow.toggleDevTools();
}
},
]
},
{
label:'刷新',
accelerator: 'F5',
role: 'reload',
},
]
let winItem = null;
const createAddWindow = () =>{
winItem = new BrowserWindow({
width: 600,
height: 300,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
winItem.loadFile('add.html')
}
const eventSub = () =>{
ipcMain.on('sub:add', (e, val)=>{
win.webContents.send('sub:add', val);
console.log(val)
winItem.close();
})
}
eventSub();
三、index.html 和 add.html
<h1>这个一个简单的electron应用12222</h1>
<script>
const electron = require('electron')
const { ipcRenderer } = electron
ipcRenderer.on('sub:add', (e, val) => {
console.log('index.html', val)
});
</script>
<button onclick="add()"> 提交 </button>
<script>
const electron = require('electron')
const { ipcRenderer } = electron
add = () => {
ipcRenderer.send('sub:add', 'add.html123');
}
</script>