Sunday, December 31, 2017

How to trigger MouseDown via PhantomJS?

Leave a Comment

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 fails to trigger the action on the site. no error returned.

2 Answers

Answers 1

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

event listeners to detect the clicks

and

commas between your multiple selectors in your jQuery line.

Please run the snippet below, which shows the modified jQuery line and the listeners running 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>

Answers 2

You will need to use the 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); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment