- 建立菜单js
- 引入menu和BrowserWindow
- 其中存在多级菜单
- 主线程(main.js)中引入
require('./main/menu.js')
//menu.js
const { Menu,BrowserWindow } = require('electron') var template = [ { label: '迷迷糊糊', submenu: [ //子菜单 { label: '精品', accelerator:'ctrl+n',//快捷键 {加速器} click: () => { //点击事件,打开新页面 var win = new BrowserWindow({ 300, height: 300, webPreferences: { nodeIntegration: true } }) win.loadFile('./html/yellow.html') win.on("closed", () => { win = null }) } }, { label: '头昏脑胀', click: () => { } } ] }, { label: '念奴娇', submenu: [ { label: '赤壁怀古', click: () => { } }, { label: '大江东去', click: () => { } } ] } ] var m = Menu.buildFromTemplate(template) Menu.setApplicationMenu(m)
右键菜单
渲染线程加 window.addEventListener('contextmenu',(e)=>{})
通过监听右键点击事件触发事件
通过menu.popup()弹出menu菜单
//import { readFile } from 'fs' window.onload = function () { var btn = this.document.querySelector('#btn') var div = this.document.querySelector('#the_div') alert("??") btn.onclick = function () { alert("启动了") // readFile('wendang.txt',(err,data)=>{ // div.innerHTML = data // }) } } const { remote } = require('electron') var right_template = [ { label: '复制' }, { label: '粘贴' } ] var m = remote.Menu.buildFromTemplate(right_template) window.addEventListener('contextmenu', (e) => { // alert(1) //阻止默认响应事件 e.preventDefault() m.popup({ window: remote.getCurrentWindow() }) })