开发者

Simulate human click in JavaScript

开发者 https://www.devze.com 2023-04-05 09:18 出处:网络
I have a small scraper where I need to click an anchor link using JavaScript. I\'ve tried a few ways: jQuery.click(), document.createEvent(\'MouseEvents\') etc. T开发者_Go百科hey all sort of worked, h

I have a small scraper where I need to click an anchor link using JavaScript. I've tried a few ways: jQuery.click(), document.createEvent('MouseEvents') etc. T开发者_Go百科hey all sort of worked, however they don't fully execute like a human click (they open a tab like they should but don't start a download).

The anchor tag has this attribute:

onclick="if (document.getElementById('ReportViewer_ctl01_ctl05_ctl00').selectedIndex == 0) return false; 
if (!ClientToolbarReportViewer_ctl01.HandleClientSideExport()) __doPostBack('ReportViewer$ctl01$ctl05$ctl01','');return false;"

I've also tried running to crux of this in the command line :

 __doPostBack('ReportViewer$ctl01$ctl05$ctl01','')

this also sort of works but not fully like a human click.

I can go into more detail if required however at the moment I am looking for a magic bullet which I think should exist.


I keep a pastebin saved of two programmatic ways to do it. It's only ever failed me when google decided to strip the window object (and every other object) of their default functions >.>

http://pastebin.com/VMHvjRaR

function callClickEvent(element){
    var evt = document.createEvent("HTMLEvents"); 
    evt.initEvent("click", true, true); 
    element.dispatchEvent(evt);
}

function callClickEvent2(element){
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(evt);
}

callClickEvent(document.getElementById("myElement"))
callClickEvent2(document.getElementById("myElement"))

MDN documentation:

  • document.createEvent
  • event.initEvent
  • event.initMouseEvent
  • element.dispatchEvent
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号