Simulate a REAL HUMAN mouse click in pure javascript?

帅比萌擦擦* 提交于 2021-02-19 07:34:42

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/55059006/simulate-a-real-human-mouse-click-in-pure-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!