QuantumCoded
QuantumCoded

Reputation: 23

Is there a way to use inspect element to select an element in Electron?

I'm looking to utilize the "Select an element in the page to inspect it" Ctrl + Shift + C utility in Chromium's developer tools in order to allow a user to select an element on an Electron application.

For example, a page or file should be loaded. Then, upon calling a function, the user should be presented with the ability to select an element as if they had opened their developer tools and pressed the inspect element button. Clicking on an element to inspect it should result in a function being called with the inspected element, without opening the developer tools. The intention is that this is a built in way to select elements on a page without the need for re-writing code to allow for this style of point, highlight, and click selection system.

The intended usage is as follows

const {app, BrowserWindow} = require('electron');

app.on('ready', function() {
    let window = new BrowserWindow();
    window.loadURL('https://stackoverflow.com/');


    // This should trigger the inspect element tool
    window.getElementFromInspector(function(element) {
        // This should be called after an element is selected with the inspect element tool
    });
});

It's not expected that window should necessarily contain a .getElementFromInspector(callback: function) method. However, the solution should be functionally similar to the proposed usage. (Even if it requires loading external JavaScript into the page, just was trying to avoid it if at all possible)

Doing some looking in Electon's API documentation gave light to the contents.inspectElement(x, y) method. This sounds as if it would allow for an element to be selected for inspection from an x,y position on the page, but mentions nothing of accessing the now inspected element remotely. I would also imagine this results in opening the developer tools if not already open, which is something that can hopefully be avoided.

EDIT: From what I've seen, I don't believe it is going to be possible easy to use the inspect element selector without having the developer tools open. Because of this, answers that require the developer tools to be open will be accepted, but it is preferred that the developer tools need not be open.

Upvotes: 1

Views: 5061

Answers (4)

georgiginaa
georgiginaa

Reputation: 31

As Muhammad said, I also used 'electron-context-menu' like this:

  1. npm install electron-context-menu
  2. I use it in electron, react with typescript like:

main.ts - at the top of the file:

import contextMenu from "electron-context-menu";

contextMenu({
  showSaveImageAs: true,
  showInspectElement: true,
});

let mainWindow: Electron.BrowserWindow | null;

(async () => {
  await app.whenReady();

  mainWindow = new BrowserWindow({
    webPreferences: {
      spellcheck: true,
    },
  });
})();

Upvotes: 0

Lạc Anh
Lạc Anh

Reputation: 1

I've found a solution for me: (Right click + Shift at Element)

main.js:

ipcMain.on('InspectMeAtPos', (ev, cursorPos) => { 
    let senderWd = BrowserWindow.fromWebContents(ev.sender)
    console.log('InspectMeAtPos : ', cursorPos)
    senderWd.webContents.inspectElement(cursorPos.x, cursorPos.y)
})

preload.js:

addEventListener('contextmenu', (ev) => {
  ev.shiftKey ? ipc.send('InspectMeAtPos', { x: ev.x, y: ev.y }) : null
})

Upvotes: 0

QuantumCoded
QuantumCoded

Reputation: 23

This accomplishes the inspect on hover over in the same way the inspect element utility does, but does not highlight the element. It also requires the developer tools to be shown to work.

// main.js
const electron = require('electron');
const path = require('path');

electron.app.on('ready', function() {
  let window = new electron.BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'inspector.js')
    }
  });

  window.webContents.openDevTools();

  electron.ipcMain.addListener('mouse', function(event, e) {
    event.returnValue = null;
    window.webContents.inspectElement(e.x, e.y);
  });

  window.loadURL('https://stackoverflow.com/');
});
// inspector.js
window.onload = function() {
  let {ipcRenderer} = require('electron');

  document.onmousemove = e => ipcRenderer.sendSync('mouse', { x: e.clientX, y: e.clientY });
};

This doesn't do exactly what I had wanted, nor does it do it in the manor I had intended, but it is the closest I've been able to get to solving this problem.

Upvotes: 1

Muhammad Umair Ghufran
Muhammad Umair Ghufran

Reputation: 865

Good News! Here a very clean solution for this.I totally understand what particular problem you're facing.

Install Electron Context Menu

If you're using Npm (learn more about NPM here)

npm install electron-context-menu

Otherwise using yarn (learn more about Yarn here)

  yarn add electron-context-menu

STEP 1: Learning how the Context Menu works

// ./main.js
const {app, BrowserWindow} = require('electron');
const contextMenu = require('electron-context-menu');

// Add an item to the context menu that appears only when you click on an image
contextMenu({
    prepend: (params, browserWindow) => [{
        label: 'Rainbow',
        // Only show it when right-clicking images
        visible: params.mediaType === 'image'
    }]
});

// Your code that starts a new application
let win;
(async () => {
    await app.whenReady();
    win = new BrowserWindow();
})();

STEP2: Adding items to the context menu with a custom behaviour

const contextMenu = require('electron-context-menu');

contextMenu({
    prepend: (params, browserWindow) => [
        {
            label: 'Destroy Atomic Bombs',
            click: (menuItem, browserWindow, event) => {
                // Note that the alert function is only avaialble in the renderer process
                //alert("You destroyed all the atomic bombs in the world, thanks :3")

                // If executed from the main process, the console log function will appear in the terminal, not in the developer tools
                console.log("You destroyed all the atomic bombs in the world, thanks :3")
            }
        }
    ]
});

detail learning for this method - Way 1 Github repo of electron-context-menu

I hope, it will help you :) Happy coding.

Upvotes: 2

Related Questions