skip to Main Content

I try to send a mouseWheel event to a BrowserWindow webContent with electron with the following code:

const wheelEvent = {
    type: 'mouseWheel',
    x: 100, // X-coordinate (optional)
    y: 100, // Y-coordinate (optional)
    deltaX: 0, // Horizontal scroll amount
    deltaY: 120, // Vertical scroll amount (e.g., 120 for one notch of scrolling)
};

// Send the event to the webview
win.webContents.sendInputEvent(wheelEvent, (result) => {
    if (!result.success) {
        console.log('Error sending input event:', result.error);
    }
});

but nothing happen, and I don’t get any error. Is it because wheel events are not trusted ? https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent

In that case mouseWheel events are no longer working with electron ?

I am sure that the browser window has the focus before running the code.

2

Answers


  1. Have you checked the status of the events using the DevTools?
    By the way Pupeeteer might help. It generates trusted events.

    Login or Signup to reply.
  2. In your code sendInputEvent method does not support synthesizing mouse wheel events directly because sendInputEvent method can only be used to simulate certain types of input events that are allowed to be synthesized by the operating system.

    To simulate mouse wheel events in Electron, you can use the webContents.executeJavaScript method to execute js code within the web page context

    const wheelEvent = new WheelEvent('wheel', {
        deltaX: 0, // Horizontal scroll amount
        deltaY: 120, // Vertical scroll amount (e.g., 120 for one notch of scrolling)
        clientX: 100, // X-coordinate
        clientY: 100, // Y-coordinate
    });
    
    // Execute JavaScript code within the web page context to dispatch the wheel event
    win.webContents.executeJavaScript(`
        document.dispatchEvent(new WheelEvent('wheel', ${JSON.stringify(wheelEvent)}));
    `).then(() => {
        console.log('Mouse wheel event dispatched successfully');
    }).catch((error) => {
        console.error('Error dispatching mouse wheel event:', error);
    });
    

    As per requirement replace win with your BrowserWindow instance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search