Skip to content

Instantly share code, notes, and snippets.

@harryi3t
Created October 9, 2019 18:43
Show Gist options
  • Save harryi3t/a79d77a8b5d42f6d0563e09d90e107d5 to your computer and use it in GitHub Desktop.
Save harryi3t/a79d77a8b5d42f6d0563e09d90e107d5 to your computer and use it in GitHub Desktop.
Electron Fiddle Gist
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<div>
<h1>Supports: Win, macOS, Linux <span>|</span> Process: Main</h1>
<div>
<div>
<button id="context-menu">View Demo</button>
</div>
<p>A context, or right-click, menu can be created with the <code>Menu</code> and <code>MenuItem</code> modules as well. You can right-click anywhere in this app or click the demo button to see an example context menu.</p>
<p>In this demo we use the <code>ipcRenderer</code> module to show the context menu when explicitly calling it from the renderer process.</p>
<p>See the full <a href="http://electron.atom.io/docs/api/web-contents/#event-context-menu">context-menu event documentation</a> for all the available properties.</p>
</div>
</div>
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
</body>
</html>
const {
BrowserWindow,
Menu,
MenuItem,
ipcMain,
app
} = require('electron')
const menu = new Menu()
menu.append(new MenuItem({ label: 'Hello' }))
menu.append(new MenuItem({ type: 'separator' }))
menu.append(new MenuItem({ label: 'Electron', type: 'checkbox', checked: true }))
let mainWindow = null
function createWindow () {
const windowOptions = {
width: 600,
height: 400,
title: 'Manage Window State',
webPreferences: {
nodeIntegration: true
}
}
mainWindow = new BrowserWindow(windowOptions)
mainWindow.loadFile('index.html')
mainWindow.on('closed', () => {
mainWindow = null
})
}
app.on('ready', () => {
createWindow()
})
app.on('browser-window-created', (event, win) => {
win.webContents.on('context-menu', (e, params) => {
menu.popup(win, params.x, params.y)
})
})
ipcMain.on('show-context-menu', (event) => {
const win = BrowserWindow.fromWebContents(event.sender)
menu.popup(win)
})
const {ipcRenderer} = require('electron')
// Tell main process to show the menu when demo button is clicked
const contextMenuBtn = document.getElementById('context-menu')
contextMenuBtn.addEventListener('click', () => {
ipcRenderer.send('show-context-menu')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment