Simple API

Every method is a simple English command: goto, refresh, click, type… you can check out Nightmare’s full API here.

Nightmare lets you simplify deeply nested callbacks into a few sequential statements. Here’s an example search on Yahoo:

Raw Phantomjs

phantom.create(function (ph) {
  ph.createPage(function (page) {
    page.open('http://yahoo.com', function (status) {
      page.evaluate(function () {
        var el =
          document.querySelector('input[title="Search"]');
        el.value = 'github nightmare';
      }, function (result) {
        page.evaluate(function () {
          var el = document.querySelector('.searchsubmit');
          var event = document.createEvent('MouseEvent');
          event.initEvent('click', true, false);
          el.dispatchEvent(event);
        }, function (result) {
          ph.exit();
        });
      });
    });
  });
});
Copy the code

With Nightmare

new Nightmare()
  .goto('yahoo.com')
  .type('input[title="Search"]', 'github nightmare')
  .click('.searchsubmit')
  .run();
Copy the code

Pluggable

You can also build plugins to repeat automated sequences in a single call.

Here’s an example where the Swiftly login sequence has been abstracted for repeated use:

/**
 * Login to a Swiftly account.
 *
 * @param {String} email
 * @param {String} password
 */

exports.login = function(email, password){
  return function(nightmare) {
    nightmare
      .viewport(800, 1600)
      .goto('https://swiftly.com/login')
        .type('#username', email)
        .type('#password', password)
        .click('.button--primary')
      .wait();
  };
};
Copy the code

. then you can use the plugin like this:

var Swiftly = require('nightmare-swiftly');
new Nightmare()
  .use(Swiftly.login(email, password))
  .use(Swiftly.task(instructions, uploads, path))
  .run();
Copy the code

Install it

Nightmare and its plugins can be installed with npm:

$ npm install nightmareCopy the code

The package exposes a Javascript API.