【问题标题】:How to add a right-click menu in Electron that has "Inspect Element" option like Chrome?如何在 Electron 中添加像 Chrome 一样具有“检查元素”选项的右键菜单?
【发布时间】:2015-12-14 16:50:33
【问题描述】:

我正在构建一个 Electron 应用程序,我想检查特定的 UI 元素。我打开了 Chrome 开发工具进行开发,但我想要的是能够像在 Google Chrome 中一样右键单击 UI 元素并选择“检查元素”。目前,右键单击在我的样板电子应用程序中没有任何作用。如何启用此功能?

【问题讨论】:

    标签: electron


    【解决方案1】:

    Electron 有一个名为win.inspectElement(x, y) 的内置函数。

    通过创建带有MenuItem 的Electron Menu,可以将此功能作为选项包含在右键单击上下文菜单中。在客户端(又名 renderer 进程)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)
    

    【讨论】:

    • 如果有人觉得它有用,我根据您的回答在 github 上创建了一个 repo。你可以在这里找到它:debug-menu
    • 在最新版本的电子 (0.36.11) 中,我必须在事件处理程序中调用 remote.getCurrentWindow() 才能使其工作,而不是缓存在 currentWindow 常量中。
    • 如果您使用打字,inspectElement 不存在于BrowserWindow。你可以改用remote.getCurrentWindow().webContents.inspectElement
    • 导入语句已更改;现在还有一个example in the docs
    【解决方案2】:

    试试electron-context-menu。它添加了inspect elementcopypaste

    【讨论】:

    • 这也适用于 Forge。!我想指出,虽然此功能不属于本机应用程序,因此应该以某种方式将其用于生产
    • 这个包制作的上下文菜单不能根据你点击的地方改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2022-12-19
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多