Basj
Basj

Reputation: 46473

How to enable right-click with Electron BrowserWindow and BrowserView?

I have a BrowserView inside a BrowserWindow (I need both indeed):

const { app, BrowserWindow, BrowserView } = require('electron');

app.on('ready', () => {
    browserWindow = new BrowserWindow({ width: 800, height: 500, frame: false });
    bv = new BrowserView({ webPreferences: { nodeIntegration: false }});
    bv.setBounds({ x: 0, y: 30, width: 800, height: 470});
    bv.webContents.loadURL('https://old.reddit.com');
    browserWindow.setBrowserView(bv);
});

Doing a right-click on web pages doesn't do anything. How to enable right-click to have "Back", "Forward", "Reload", "Copy", "Paste", etc. as usual with Chrome?

enter image description here

Upvotes: 5

Views: 12867

Answers (1)

Mark
Mark

Reputation: 1679

Electron has some sample menus up on their docs located at https://electronjs.org/docs/api/menu

// Importing this adds a right-click menu with 'Inspect Element' option
const remote = require('remote')
const Menu = remote.require('menu')
const MenuItem = remote.require('menu-item')

let rightClickPosition = null

const menu = new Menu()
const menuItem = new MenuItem({
  label: 'Inspect Element',
  click: () => {
    remote.getCurrentWindow().inspectElement(rightClickPosition.x, rightClickPosition.y)
  }
})
menu.append(menuItem)

window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  rightClickPosition = {x: e.x, y: e.y}
  menu.popup(remote.getCurrentWindow())
}, false)

Following this template you could set up custom roles like Back, Forward, Reload, etc. using custom javascript like this:

Back
const backMenuItem = new MenuItem({
  label: 'Back',
  click: () => {
    window.history.back();
  }
})
menu.append(backMenuItem)

Forward
const forwardMenuItem = new MenuItem({
  label: 'Forward',
  click: () => {
    window.history.forward();
  }
})
menu.append(forwardMenuItem)

Upvotes: 8

Related Questions