electron 自定义右键菜单
生活随笔
收集整理的這篇文章主要介紹了
electron 自定义右键菜单
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
實(shí)現(xiàn)思路
1.使用@electron/remote模塊實(shí)現(xiàn)
1.0 監(jiān)聽右鍵,并阻止默認(rèn)行為
下面的代碼阻止HTML頁面右鍵彈出默認(rèn)的右鍵菜單。并在渲染進(jìn)程控制臺(tái)中輸出字符串信息"你點(diǎn)擊的右鍵"。
window.onload = ()=>{window.addEventListener("contextmenu",(e)=>{e.preventDefault() //阻止默認(rèn)行為console.log("你點(diǎn)擊的右鍵")}) }在上面代碼的基礎(chǔ)上結(jié)合之前學(xué)習(xí)的menu和remote,共同實(shí)現(xiàn)渲染進(jìn)程中的右鍵菜單。
1.1 main.js
主要是實(shí)現(xiàn)remote的引入與設(shè)置。可以參看:electron新版本中使用remote - 在主程序中引入和初始化
const { app,BrowserWindow,ipcMain,shell} = require("electron") const remote = require("@electron/remote/main") //1 remote.initialize()//2let mainWindow = nullapp.on("ready",()=>{mainWindow = new BrowserWindow({width:300,height:300,webPreferences:{nodeIntegration:true,//允許渲染進(jìn)程使用nodejscontextIsolation:false//允許渲染進(jìn)程使用nodejs}})mainWindow.loadFile("index.html")mainWindow.on("closed",()=>{mainWindow = null})remote.enable(mainWindow.webContents)//3 })1.2 index.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>利用remote實(shí)現(xiàn)右鍵菜單</title></head> <body> <script src="popupmenu.js"></script> </body> </html>1.3 popupmenu.js
const remote = require("@electron/remote") const Menu = remote.Menuconst menu_tpl = [{label:"文件",submenu:[{label:"新建"},{label:"打開"},{label:"保存"},]},{label:"編輯",submenu:[{label:"撤銷"},{label:"重做"},{label:"清空"},]}, ]const context_menu = Menu.buildFromTemplate(menu_tpl)window.onload = ()=>{window.addEventListener("contextmenu",(e)=>{e.preventDefault() //阻止默認(rèn)行為//彈出右鍵菜單context_menu.popup({window:remote.getCurrentWindow()})}) }運(yùn)行后效果
2.使用主進(jìn)程和渲染進(jìn)程通信實(shí)現(xiàn)
總結(jié)
以上是生活随笔為你收集整理的electron 自定义右键菜单的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Wiki引擎mediawiki
- 下一篇: Linux是操作系统吗?GNU/Linu