Simulate a REAL HUMAN mouse click in pure javascript?
Asked Answered
E

1

11

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!

Epizoon answered 8/3, 2019 at 8:6 Comment(5)
You can't simulate it with any in-browser API. You can write/use a separate utility that communicates with your extension via nativeMessaging API and sends a low-level mouse event using the API of the OS itself (e.g. WINAPI in Windows).Dean
@wOxxOm if you don't mind can you give me some more info sir?Epizoon
I don't have any more info so try searching for existing solutions or implement one yourself from ground up.Dean
This approach doesn't change isTrusted property (since it is read only), but it might work.Icehouse
@IvánNokonoko thanks a lot dude it works !Epizoon
C
29

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);
Claresta answered 8/3, 2019 at 18:5 Comment(7)
Really helped in clicking an element when using Puppeteer.Quin
I upvoted your answer using your code. I used this selector: #answer-55068681 > div > div.votecell.post-layout--left > div > button.js-vote-up-btn.flex--item.s-btn.s-btn__unset.c-pointerEmmanuelemmeline
In Tampermonkey I got this message Uncaught TypeError: elemnt1.dispatchEvent is not a functionImidazole
@HarisurRehman Hello, have you been able to simulate a human scroll in Puppeteer? I'm not sure that normal events will suffice.Goodbye
@LeninZapata well scroll didn't give me any problem in the past. Traditional puppeteer code to scroll always worked for me.Quin
@HarisurRehman Ok I'm going to try, I want to do everything possible to be undetectableGoodbye
this doesn't work on an input elementSubstrate

© 2022 - 2024 — McMap. All rights reserved.