Wso
Wso

Reputation: 302

How to use nightmare to press arrow key?

Is there any way to use nightmare (the nodeJS module) to press an arrow key? Either by sending the key to the specific element or by clicking on the element and sending the keypress to the page as a whole?

My problem is that there is a dropdown menu which, when clicked on, displays some options below it. These options do not appear to be clickable, I have tried click and even the realClick nightmare extension. Neither seem able of selecting any element of the dropdown. While playing around with the page, I found that by using the arrow keys and the enter key, I could select the options without clicking. So is there any way to send the keypress events to electron? Either through nightmare or by accessing electron directly?

Upvotes: 1

Views: 707

Answers (1)

devilpreet
devilpreet

Reputation: 767

It is called auto complete menu and there is no standard way of doing it. I tried working with Google and came up with a method. I think, it will be tough to make generic solution, as it depends on how auto complete is implemented. Hope this helps!

var Nightmare = require('nightmare');

var nightmare = Nightmare({
  show: true,
  webPreferences: {}
})

nightmare
  .goto('http://www.google.co.in')
  .evaluate(function(searchTerm) {
    var elem = document.querySelector('#lst-ib');
    elem.value = searchTerm;

    //Do mousedown to initiate auto complete window
    var event = document.createEvent('MouseEvent');
    event.initEvent('mousedown', true, true);
    elem.dispatchEvent(event);
  }, 'Leo')
  .then(function() {
    //Wait for results to appear
    nightmare.wait(1000)
    .evaluate(function() {
      //Click the first option of List
      var first = document.querySelector('#sbtc > div.gstl_0.sbdd_a > div:nth-child(2) > div.sbdd_b > div > ul > li:nth-child(1)');
      first.firstElementChild.click();
    }).then(function() {
      console.log('All Done');
    });
  });

Upvotes: 1

Related Questions