我目前正在研究chrome扩展,扩展必须自动执行某些过程,但在页面中单击元素时会执行一些操作,但是当我以编程方式使用JavaScript单击元素时,没有任何反应。
有谁知道如何像真人一样点击它?
event.isTrusted // readonly property
但我怎么能把它作为event.isTrusted = true?
我认为该网站使用click事件的isTrusted属性制作了一些预防方法!
来自this answer:
试试这个代码;它通过在按钮中心触发的快速连续的mousedown,mouseup和click事件模拟鼠标左键单击元素:
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);