I'm trying to include Inspect element right click into my electron app, I found a previous post about this but this is 4 years old and I don't know where to include this. I already managed to get devtools to open automatically but now I want to add right click inspect element. My question is.
How and where do I add inspect element as right click to work globally throughout my app and how do I make dev-tools open with a shortcut. currently I automatically open Devtools in the main.js script but when I click it away I got no way of bringing it back. Thanks for the help in advance.
Add the following code to your window's renderer process code. Note that you may have to adapt the first two lines, depending on which API elements are already defined...
const { remote, webFrame } = require ('electron');
const { getCurrentWebContents, Menu, MenuItem } = remote;
//
let rightClickPosition;
//
const contextMenu = new Menu ();
const menuItem = new MenuItem
(
{
label: 'Inspect Element',
click: () =>
{
let factor = webFrame.getZoomFactor ();
let x = Math.round (rightClickPosition.x * factor);
let y = Math.round (rightClickPosition.y * factor);
getCurrentWebContents ().inspectElement (x, y);
}
}
);
contextMenu.append (menuItem);
//
window.addEventListener
(
'contextmenu',
(event) =>
{
event.preventDefault ();
rightClickPosition = { x: event.x, y: event.y };
contextMenu.popup ();
},
false
);
References:
As for how to have devTools open with a shortcut, this would automatically happen if your menu bar contains a submenu with a menu item whose role is toggledevtools. For instance, in your main process code, adding this to your menu template would provide a Toggle Developer Tools menu item with standard keyboard shortcut:
{
label: "Developer",
submenu:
[
{ role: 'reload' },
{ role: 'toggledevtools' }
]
}
Reference: Menu Item Roles
UPDATE:
It appears there is a more powerful and flexible way of handling a contextual menu at the webContents level, by listening to a 'context-menu' event, documented since Electron 1.0.2.
One important feature is that the zoom factor doesn't need to be taken into account any more, the x and y coordinates returned in params are just always right.
Reference: webContents Event: 'context-menu'
Here is some alternative renderer process code using this method:
const { getCurrentWebContents, Menu, MenuItem } = require ('electron').remote;
//
let webContents = getCurrentWebContents ();
//
let rightClickPosition;
//
const contextMenu = new Menu ();
const menuItem = new MenuItem
(
{
label: 'Inspect Element',
click: () =>
{
webContents.inspectElement (rightClickPosition.x, rightClickPosition.y);
}
}
);
contextMenu.append (menuItem);
//
webContents.on
(
'context-menu',
(event, params) =>
{
rightClickPosition = { x: params.x, y: params.y };
contextMenu.popup ();
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With