Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 723
Arturino Avatar asked Mar 01 '17 20:03

Arturino


2 Answers

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>
like image 83
JMA Avatar answered Oct 19 '22 05:10

JMA


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);
like image 45
Gillsoft AB Avatar answered Oct 19 '22 03:10

Gillsoft AB