简体   繁体   中英

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?

在此处输入图片说明

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM