Janaravi
Janaravi

Reputation: 155

Simulate a REAL HUMAN mouse click in pure javascript?

I'm currently working on a chrome extension and the extension has to automate some process but in the page when I click the element some action performed but when I click the element programmatically with JavaScript nothing happens.

Does anyone know how to click it like real human ?

event.isTrusted // readonly property

but how can i make it as a event.isTrusted = true?

I think the website made some prevention method with the isTrusted property of the click event!

Upvotes: 11

Views: 14651

Answers (1)

Iván Nokonoko
Iván Nokonoko

Reputation: 5118

From this answer:

Try with this code; it simulates a mouse left click on the element by a quick succession of mousedown, mouseup and click events fired in the center of the button:

var simulateMouseEvent = function(element, eventName, coordX, coordY) {
  element.dispatchEvent(new MouseEvent(eventName, {
    view: window,
    bubbles: true,
    cancelable: true,
    clientX: coordX,
    clientY: coordY,
    button: 0
  }));
};

var theButton = document.querySelector('ul form button');

var box = theButton.getBoundingClientRect(),
        coordX = box.left + (box.right - box.left) / 2,
        coordY = box.top + (box.bottom - box.top) / 2;

simulateMouseEvent (theButton, "mousedown", coordX, coordY);
simulateMouseEvent (theButton, "mouseup", coordX, coordY);
simulateMouseEvent (theButton, "click", coordX, coordY);

Upvotes: 29

Related Questions