Search code examples
javascriptgoogle-chrome-extensionmouseeventmouseclick-event

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!


Solution

  • 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);