robot | move mouse | send keys | Search

The clickMouse function uses the node-screenshots and mouse-controller modules to simulate a left mouse click at a specified position (x, y) on the primary monitor. This function is exported as a module, making it available for use in other scripts.

Run example

npm run import -- "mouse click"

mouse click

const { Monitor } = require("node-screenshots")
const MouseController = require('mouse-controller')
const mc = new MouseController();

function clickMouse(x, y) {
  let monitors = Monitor.all()
  monitors.sort((a, b) => (a.x + a.y) - (b.x + b.y))
  /*console.log({
    x: monitors[0].x,
    y: monitors[0].y,
    width: monitors[0].width,
    height: monitors[0].height,
  })*/
  mc.click(mc.BUTTON.LEFT, {x: x * monitors[0].width * 3 + monitors[0].x, y: y * monitors[0].height})
}

module.exports = clickMouse

What the code could have been:

const { Monitor } = require('node-screenshots');
const MouseController = require('mouse-controller');

/**
 * Clicks the left mouse button at the specified coordinates, taking into account the screen resolution.
 * 
 * @param {number} x The x-coordinate of the click.
 * @param {number} y The y-coordinate of the click.
 * @return {void}
 */
class MouseControllerWrapper {
  /**
   * Initialize the mouse controller.
   */
  constructor() {
    this.mc = new MouseController();
  }

  /**
   * Get all monitors and sort them in descending order based on their area.
   * 
   * @return {Array} An array of monitors, sorted by area.
   */
  getMonitors() {
    return Monitor.all().sort((a, b) => (b.width * b.height) - (a.width * a.height));
  }

  /**
   * Click the left mouse button at the specified coordinates.
   * 
   * @param {number} x The x-coordinate of the click.
   * @param {number} y The y-coordinate of the click.
   * @return {void}
   */
  click(x, y) {
    const monitors = this.getMonitors();
    const monitor = monitors[0];
    const scaledX = (x * monitor.width) + monitor.x;
    const scaledY = (y * monitor.height) * 3; // TODO: Validate the 3x scale factor
    this.mc.click(this.mc.BUTTON.LEFT, { x: scaledX, y: scaledY });
  }
}

const clickMouse = new MouseControllerWrapper();

module.exports = clickMouse.click;

Code Breakdown

Dependencies

Functions

clickMouse(x, y)

Export