如何使用Electron BrowserWindow和BrowserView启用右键单击?

时间:2019-03-15 18:13:56

标签: javascript google-chrome browser electron contextmenu

我在BrowserView中有一个BrowserWindow(我确实需要两者):

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);
});

右键单击网页不会执行任何操作。 如何通过右键单击使Chrome像往常一样具有“上一步”,“前进”,“重新加载”,“复制”,“粘贴”等?

enter image description here

1 个答案:

答案 0 :(得分:2)

Electron的文档位于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)

按照此模板,您可以使用如下自定义javascript设置自定义角色,例如BackForwardReload等。

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)