如何在Electron中添加具有“检查元素”的右键菜单?选择像Chrome?
我正在构建一个Electron应用程序,我想检查特定的UI元素。我已经开放了Chrome开发工具进行开发,但是我想要的是能够像在Google Chrome中一样右键单击UI元素并选择检查元素。目前,在我的样板电子应用程序中,单击鼠标右键不起作用。我该如何启用它?
I'm building an Electron application and I would like to inspect specific UI elements. I have the Chrome dev tools open for development, but what I want is to be able to right-click a UI element and choose "Inspect Element" like I can in Google Chrome. Currently, right-clicking doesn't do anything in my boilerplate Electron app. How can I enable this?
电子具有一个称为 win.inspectElement(x,y)。
可以通过创建带有 MenuItem的Electron
。在客户端(也称为 renderer 进程)JavaScript中调用以下代码: Menu
来在右键单击上下文菜单中将此功能作为选项包含在内
Including this function as an option in a right-click context menu is possible by creating an Electron Menu
with a MenuItem
. Call the following in the client (aka renderer process) Javascript:
// 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)