How to launch MouseDown through PhantomJS?

I tried:

var clickEvent = document.createEvent('MouseEvents'); clickEvent.initEvent("mousedown", true, true); jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0].dispatchEvent(clickEvent); 

but it just doesnโ€™t start the action on the site. the error is not returned.

+6
source share
2 answers

So you programmatically trigger a click on the DOM element with the "mousedown" event. To answer your question you need to have two things in your source code:

click listen event listeners

and

between your multiple selectors in your jQuery string.

Please run the snippet below which shows that the modified jQuery string and listeners are working correctly.

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { // You must have event listeners to see if anything is actually happening. For example, here I will add only a listener to the first element: jQuery(".left-rail-facets")[0].addEventListener('mousedown', function(e) { jQuery(".left-rail-facets")[0].innerHTML = "I have received a click."; }, false); // Now here is the code from your question. Please see how I have commas instead of spaces in my jQuery selector: var clickEvent = document.createEvent('MouseEvents'); clickEvent.initEvent('mousedown', true, true); jQuery('.left-rail-facets,.facet-list,.facet.CS,.suggestion[data-value="B"],a')[0].dispatchEvent(clickEvent); }); </script> </head> <body> <h1>I am a Webpage</h1> <p class="left-rail-facets">I have not received a click.</p> <p class="facet-list">I have not received a click.</p> <facet class="CS">I have not received a click.</facet> <p class="suggestion" data-value="B">I have not received a click.</p> <a href="url">I have not received a click.</a> </body> </html> 
+4
source

You will need to use document.createEvent and event.initMouseEvent:

 var element = document.querySelector('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a'); //or var element = jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0]; var elementRect = element.getBoundingClientRect(); var mouseEvent = document.createEvent('MouseEvents'); mouseEvent.initMouseEvent('mousedown', true, true, window, 0, elementRect.left, elementRect.top); 
+1
source

Source: https://habr.com/ru/post/1015383/


All Articles