Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

nightmare

segmentio30kMIT3.0.2TypeScript support: definitely-typed

A high-level browser automation library.

nightmare, electron

readme

Build Status Join the chat at https://gitter.im/rosshinkley/nightmare

Nightmare

Nightmare is a high-level browser automation library from Segment.

The goal is to expose a few simple methods that mimic user actions (like goto, type and click), with an API that feels synchronous for each block of scripting, rather than deeply nested callbacks. It was originally designed for automating tasks across sites that don't have APIs, but is most often used for UI testing and crawling.

Under the covers it uses Electron, which is similar to PhantomJS but roughly twice as fast and more modern.

⚠️ Security Warning: We've implemented many of the security recommendations outlined by Electron to try and keep you safe, but undiscovered vulnerabilities may exist in Electron that could allow a malicious website to execute code on your computer. Avoid visiting untrusted websites.

🛠 Migrating to 3.x: You'll want to check out this issue before upgrading. We've worked hard to make improvements to nightmare while limiting the breaking changes and there's a good chance you won't need to do anything.

Niffy is a perceptual diffing tool built on Nightmare. It helps you detect UI changes and bugs across releases of your web app.

Daydream is a complementary chrome extension built by @stevenmiller888 that generates Nightmare scripts for you while you browse.

Many thanks to @matthewmueller and @rosshinkley for their help on Nightmare.

Examples

Let's search on DuckDuckGo:

const Nightmare = require('nightmare')
const nightmare = Nightmare({ show: true })

nightmare
  .goto('https://duckduckgo.com')
  .type('#search_form_input_homepage', 'github nightmare')
  .click('#search_button_homepage')
  .wait('#r1-0 a.result__a')
  .evaluate(() => document.querySelector('#r1-0 a.result__a').href)
  .end()
  .then(console.log)
  .catch(error => {
    console.error('Search failed:', error)
  })

You can run this with:

npm install --save nightmare
node example.js

Or, let's run some mocha tests:

const Nightmare = require('nightmare')
const chai = require('chai')
const expect = chai.expect

describe('test duckduckgo search results', () => {
  it('should find the nightmare github link first', function(done) {
    this.timeout('10s')

    const nightmare = Nightmare()
    nightmare
      .goto('https://duckduckgo.com')
      .type('#search_form_input_homepage', 'github nightmare')
      .click('#search_button_homepage')
      .wait('#links .result__a')
      .evaluate(() => document.querySelector('#links .result__a').href)
      .end()
      .then(link => {
        expect(link).to.equal('https://github.com/segmentio/nightmare')
        done()
      })
  })
})

You can see examples of every function in the tests here.

To get started with UI Testing, check out this quick start guide.

To install dependencies

npm install

To run the mocha tests

npm test

Node versions

Nightmare is intended to be run on NodeJS 4.x or higher.

API

Nightmare(options)

Creates a new instance that can navigate around the web. The available options are documented here, along with the following nightmare-specific options.

waitTimeout (default: 30s)

Throws an exception if the .wait() didn't return true within the set timeframe.

const nightmare = Nightmare({
  waitTimeout: 1000 // in ms
})
gotoTimeout (default: 30s)

Throws an exception if the .goto() didn't finish loading within the set timeframe. Note that, even though goto normally waits for all the resources on a page to load, a timeout exception is only raised if the DOM itself has not yet loaded.

const nightmare = Nightmare({
  gotoTimeout: 1000 // in ms
})
loadTimeout (default: infinite)

Forces Nightmare to move on if a page transition caused by an action (eg, .click()) didn't finish within the set timeframe. If loadTimeout is shorter than gotoTimeout, the exceptions thrown by gotoTimeout will be suppressed.

const nightmare = Nightmare({
  loadTimeout: 1000 // in ms
})
executionTimeout (default: 30s)

The maximum amount of time to wait for an .evaluate() statement to complete.

const nightmare = Nightmare({
  executionTimeout: 1000 // in ms
})
paths

The default system paths that Electron knows about. Here's a list of available paths: https://github.com/atom/electron/blob/master/docs/api/app.md#appgetpathname

You can overwrite them in Nightmare by doing the following:

const nightmare = Nightmare({
  paths: {
    userData: '/user/data'
  }
})
switches

The command line switches used by the Chrome browser that are also supported by Electron. Here's a list of supported Chrome command line switches: https://github.com/atom/electron/blob/master/docs/api/chrome-command-line-switches.md

const nightmare = Nightmare({
  switches: {
    'proxy-server': '1.2.3.4:5678',
    'ignore-certificate-errors': true
  }
})
electronPath

The path to the prebuilt Electron binary. This is useful for testing on different versions of Electron. Note that Nightmare only supports the version on which this package depends. Use this option at your own risk.

const nightmare = Nightmare({
  electronPath: require('electron')
})
dock (OS X)

A boolean to optionally show the Electron icon in the dock (defaults to false). This is useful for testing purposes.

const nightmare = Nightmare({
  dock: true
})
openDevTools

Optionally shows the DevTools in the Electron window using true, or use an object hash containing mode: 'detach' to show in a separate window. The hash gets passed to contents.openDevTools() to be handled. This is also useful for testing purposes. Note that this option is honored only if show is set to true.

const nightmare = Nightmare({
  openDevTools: {
    mode: 'detach'
  },
  show: true
})
typeInterval (default: 100ms)

How long to wait between keystrokes when using .type().

const nightmare = Nightmare({
  typeInterval: 20
})
pollInterval (default: 250ms)

How long to wait between checks for the .wait() condition to be successful.

const nightmare = Nightmare({
  pollInterval: 50 //in ms
})
maxAuthRetries (default: 3)

Defines the number of times to retry an authentication when set up with .authenticate().

const nightmare = Nightmare({
  maxAuthRetries: 3
})

certificateSubjectName

A string to determine the client certificate selected by electron. If this options is set, the select-client-certificate event will be set to loop through the certificateList and find the first certificate that matches subjectName on the electron Certificate Object.

const nightmare = Nightmare({
  certificateSubjectName: 'tester'
})

.engineVersions()

Gets the versions for Electron and Chromium.

.useragent(useragent)

Sets the useragent used by electron.

.authentication(user, password)

Sets the user and password for accessing a web page using basic authentication. Be sure to set it before calling .goto(url).

.end()

Completes any queue operations, disconnect and close the electron process. Note that if you're using promises, .then() must be called after .end() to run the .end() task. Also note that if using an .end() callback, the .end() call is equivalent to calling .end() followed by .then(fn). Consider:

nightmare
  .goto(someUrl)
  .end(() => 'some value')
  //prints "some value"
  .then(console.log)

.halt(error, done)

Clears all queued operations, kills the electron process, and passes error message or 'Nightmare Halted' to an unresolved promise. Done will be called after the process has exited.

Interact with the Page

.goto(url[, headers])

Loads the page at url. Optionally, a headers hash can be supplied to set headers on the goto request.

When a page load is successful, goto returns an object with metadata about the page load, including:

  • url: The URL that was loaded
  • code: The HTTP status code (e.g. 200, 404, 500)
  • method: The HTTP method used (e.g. "GET", "POST")
  • referrer: The page that the window was displaying prior to this load or an empty string if this is the first page load.
  • headers: An object representing the response headers for the request as in {header1-name: header1-value, header2-name: header2-value}

If the page load fails, the error will be an object with the following properties:

Note that any valid response from a server is considered “successful.” That means things like 404 “not found” errors are successful results for goto. Only things that would cause no page to appear in the browser window, such as no server responding at the given address, the server hanging up in the middle of a response, or invalid URLs, are errors.

You can also adjust how long goto will wait before timing out by setting the gotoTimeout option on the Nightmare constructor.

.back()

Goes back to the previous page.

.forward()

Goes forward to the next page.

.refresh()

Refreshes the current page.

.click(selector)

Clicks the selector element once.

.mousedown(selector)

Mousedowns the selector element once.

.mouseup(selector)

Mouseups the selector element once.

.mouseover(selector)

Mouseovers the selector element once.

.mouseout(selector)

Mouseout the selector element once.

.type(selector[, text])

Enters the text provided into the selector element. Empty or falsey values provided for text will clear the selector's value.

.type() mimics a user typing in a textbox and will emit the proper keyboard events.

Key presses can also be fired using Unicode values with .type(). For example, if you wanted to fire an enter key press, you would write .type('body', '\u000d').

If you don't need the keyboard events, consider using .insert() instead as it will be faster and more robust.

.insert(selector[, text])

Similar to .type(), .insert() enters the text provided into the selector element. Empty or falsey values provided for text will clear the selector's value.

.insert() is faster than .type() but does not trigger the keyboard events.

.check(selector)

Checks the selector checkbox element.

.uncheck(selector)

Unchecks the selector checkbox element.

.select(selector, option)

Changes the selector dropdown element to the option with attribute [value=option]

.scrollTo(top, left)

Scrolls the page to desired position. top and left are always relative to the top left corner of the document.

.viewport(width, height)

Sets the viewport size.

.inject(type, file)

Injects a local file onto the current page. The file type must be either js or css.

.evaluate(fn[, arg1, arg2,...])

Invokes fn on the page with arg1, arg2,.... All the args are optional. On completion it returns the return value of fn. Useful for extracting information from the page. Here's an example:

const selector = 'h1'
nightmare
  .evaluate(selector => {
    // now we're executing inside the browser scope.
    return document.querySelector(selector).innerText
  }, selector) // <-- that's how you pass parameters from Node scope to browser scope
  .then(text => {
    // ...
  })

Error-first callbacks are supported as a part of evaluate(). If the arguments passed are one fewer than the arguments expected for the evaluated function, the evaluation will be passed a callback as the last parameter to the function. For example:

const selector = 'h1'
nightmare
  .evaluate((selector, done) => {
    // now we're executing inside the browser scope.
    setTimeout(
      () => done(null, document.querySelector(selector).innerText),
      2000
    )
  }, selector)
  .then(text => {
    // ...
  })

Note that callbacks support only one value argument (eg function(err, value)). Ultimately, the callback will get wrapped in a native Promise and only be able to resolve a single value.

Promises are also supported as a part of evaluate(). If the return value of the function has a then member, .evaluate() assumes it is waiting for a promise. For example:

const selector = 'h1';
nightmare
  .evaluate((selector) => (
    new Promise((resolve, reject) => {
      setTimeout(() => resolve(document.querySelector(selector).innerText), 2000);
    )}, selector)
  )
  .then((text) => {
    // ...
  })

.wait(ms)

Waits for ms milliseconds e.g. .wait(5000).

.wait(selector)

Waits until the element selector is present e.g. .wait('#pay-button').

.wait(fn[, arg1, arg2,...])

Waits until the fn evaluated on the page with arg1, arg2,... returns true. All the args are optional. See .evaluate() for usage.

.header(header, value)

Adds a header override for all HTTP requests. If header is undefined, the header overrides will be reset.

Extract from the Page

.exists(selector)

Returns whether the selector exists or not on the page.

.visible(selector)

Returns whether the selector is visible or not.

.on(event, callback)

Captures page events with the callback. You have to call .on() before calling .goto(). Supported events are documented here.

Additional "page" events
.on('page', function(type="error", message, stack))

This event is triggered if any javascript exception is thrown on the page. But this event is not triggered if the injected javascript code (e.g. via .evaluate()) is throwing an exception.

"page" events

Listens for window.addEventListener('error'), alert(...), prompt(...) & confirm(...).

.on('page', function(type="error", message, stack))

Listens for top-level page errors. This will get triggered when an error is thrown on the page.

.on('page', function(type="alert", message))

Nightmare disables window.alert from popping up by default, but you can still listen for the contents of the alert dialog.

.on('page', function(type="prompt", message, response))

Nightmare disables window.prompt from popping up by default, but you can still listen for the message to come up. If you need to handle the confirmation differently, you'll need to use your own preload script.

.on('page', function(type="confirm", message, response))

Nightmare disables window.confirm from popping up by default, but you can still listen for the message to come up. If you need to handle the confirmation differently, you'll need to use your own preload script.

.on('console', function(type [, arguments, ...]))

type will be either log, warn or error and arguments are what gets passed from the console. This event is not triggered if the injected javascript code (e.g. via .evaluate()) is using console.log.

.once(event, callback)

Similar to .on(), but captures page events with the callback one time.

.removeListener(event, callback)

Removes a given listener callback for an event.

.screenshot([path][, clip])

Takes a screenshot of the current page. Useful for debugging. The output is always a png. Both arguments are optional. If path is provided, it saves the image to the disk. Otherwise it returns a Buffer of the image data. If clip is provided (as documented here), the image will be clipped to the rectangle.

.html(path, saveType)

Saves the current page as html as files to disk at the given path. Save type options are here.

.pdf(path, options)

Saves a PDF to the specified path. Options are here.

.title()

Returns the title of the current page.

.url()

Returns the url of the current page.

.path()

Returns the path name of the current page.

Cookies

.cookies.get(name)

Gets a cookie by it's name. The url will be the current url.

.cookies.get(query)

Queries multiple cookies with the query object. If a query.name is set, it will return the first cookie it finds with that name, otherwise it will query for an array of cookies. If no query.url is set, it will use the current url. Here's an example:

// get all google cookies that are secure
// and have the path `/query`
nightmare
  .goto('http://google.com')
  .cookies.get({
    path: '/query',
    secure: true
  })
  .then(cookies => {
    // do something with the cookies
  })

Available properties are documented here: https://github.com/atom/electron/blob/master/docs/api/session.md#sescookiesgetdetails-callback

.cookies.get()

Gets all the cookies for the current url. If you'd like get all cookies for all urls, use: .get({ url: null }).

.cookies.set(name, value)

Sets a cookie's name and value. This is the most basic form, and the url will be the current url.

Sets a cookie. If cookie.url is not set, it will set the cookie on the current url. Here's an example:

nightmare
  .goto('http://google.com')
  .cookies.set({
    name: 'token',
    value: 'some token',
    path: '/query',
    secure: true
  })
  // ... other actions ...
  .then(() => {
    // ...
  })

Available properties are documented here: https://github.com/atom/electron/blob/master/docs/api/session.md#sescookiessetdetails-callback

.cookies.set(cookies)

Sets multiple cookies at once. cookies is an array of cookie objects. Take a look at the .cookies.set(cookie) documentation above for a better idea of what cookie should look like.

.cookies.clear([name])

Clears a cookie for the current domain. If name is not specified, all cookies for the current domain will be cleared.

nightmare
  .goto('http://google.com')
  .cookies.clear('SomeCookieName')
  // ... other actions ...
  .then(() => {
    // ...
  })

.cookies.clearAll()

Clears all cookies for all domains.

nightmare
  .goto('http://google.com')
  .cookies.clearAll()
  // ... other actions ...
  .then(() => {
    //...
  })

Proxies

Proxies are supported in Nightmare through switches.

If your proxy requires authentication you also need the authentication call.

The following example not only demonstrates how to use proxies, but you can run it to test if your proxy connection is working:

import Nightmare from 'nightmare';

const proxyNightmare = Nightmare({
  switches: {
    'proxy-server': 'my_proxy_server.example.com:8080' // set the proxy server here ...
  },
  show: true
});

proxyNightmare
  .authentication('proxyUsername', 'proxyPassword') // ... and authenticate here before `goto`
  .goto('http://www.ipchicken.com')
  .evaluate(() => {
    return document.querySelector('b').innerText.replace(/[^\d\.]/g, '');
  })
  .end()
  .then((ip) => { // This will log the Proxy's IP
    console.log('proxy IP:', ip);
  });

// The rest is just normal Nightmare to get your local IP
const regularNightmare = Nightmare({ show: true });

regularNightmare
  .goto('http://www.ipchicken.com')
  .evaluate(() =>
    document.querySelector('b').innerText.replace(/[^\d\.]/g, '');
  )
  .end()
  .then((ip) => { // This will log the your local IP
    console.log('local IP:', ip);
  });

Promises

By default, Nightmare uses default native ES6 promises. You can plug in your favorite ES6-style promises library like bluebird or q for convenience!

Here's an example:

var Nightmare = require('nightmare')

Nightmare.Promise = require('bluebird')
// OR:
Nightmare.Promise = require('q').Promise

You can also specify a custom Promise library per-instance with the Promise constructor option like so:

var Nightmare = require('nightmare')

var es6Nightmare = Nightmare()
var bluebirdNightmare = Nightmare({
  Promise: require('bluebird')
})

var es6Promise = es6Nightmare
  .goto('https://github.com/segmentio/nightmare')
  .then()
var bluebirdPromise = bluebirdNightmare
  .goto('https://github.com/segmentio/nightmare')
  .then()

es6Promise.isFulfilled() // throws: `TypeError: es6EndPromise.isFulfilled is not a function`
bluebirdPromise.isFulfilled() // returns: `true | false`

Extending Nightmare

Nightmare.action(name, [electronAction|electronNamespace], action|namespace)

You can add your own custom actions to the Nightmare prototype. Here's an example:

Nightmare.action('size', function(done) {
  this.evaluate_now(() => {
    const w = Math.max(
      document.documentElement.clientWidth,
      window.innerWidth || 0
    )
    const h = Math.max(
      document.documentElement.clientHeight,
      window.innerHeight || 0
    )
    return {
      height: h,
      width: w
    }
  }, done)
})

Nightmare()
  .goto('http://cnn.com')
  .size()
  .then(size => {
    //... do something with the size information
  })

Remember, this is attached to the static class Nightmare, not the instance.

You'll notice we used an internal function evaluate_now. This function is different than nightmare.evaluate because it runs it immediately, whereas nightmare.evaluate is queued.

An easy way to remember: when in doubt, use evaluate. If you're creating custom actions, use evaluate_now. The technical reason is that since our action has already been queued and we're running it now, we shouldn't re-queue the evaluate function.

We can also create custom namespaces. We do this internally for nightmare.cookies.get and nightmare.cookies.set. These are useful if you have a bundle of actions you want to expose, but it will clutter up the main nightmare object. Here's an example of that:

Nightmare.action('style', {
  background(done) {
    this.evaluate_now(
      () => window.getComputedStyle(document.body, null).backgroundColor,
      done
    )
  }
})

Nightmare()
  .goto('http://google.com')
  .style.background()
  .then(background => {
    // ... do something interesting with background
  })

You can also add custom Electron actions. The additional Electron action or namespace actions take name, options, parent, win, renderer, and done. Note the Electron action comes first, mirroring how .evaluate() works. For example:

Nightmare.action(
  'clearCache',
  (name, options, parent, win, renderer, done) => {
    parent.respondTo('clearCache', done => {
      win.webContents.session.clearCache(done)
    })
    done()
  },
  function(done) {
    this.child.call('clearCache', done)
  }
)

Nightmare()
  .clearCache()
  .goto('http://example.org')
  //... more actions ...
  .then(() => {
    // ...
  })

...would clear the browser’s cache before navigating to example.org.

See this document for more details on creating custom actions.

.use(plugin)

nightmare.use is useful for reusing a set of tasks on an instance. Check out nightmare-swiftly for some examples.

Custom preload script

If you need to do something custom when you first load the window environment, you can specify a custom preload script. Here's how you do that:

import path from 'path'

const nightmare = Nightmare({
  webPreferences: {
    preload: path.resolve('custom-script.js')
    //alternative: preload: "absolute/path/to/custom-script.js"
  }
})

The only requirement for that script is that you'll need the following prelude:

window.__nightmare = {}
__nightmare.ipc = require('electron').ipcRenderer

To benefit of all of nightmare's feedback from the browser, you can instead copy the contents of nightmare's preload script.

Storage Persistence between nightmare instances

By default nightmare will create an in-memory partition for each instance. This means that any localStorage or cookies or any other form of persistent state will be destroyed when nightmare is ended. If you would like to persist state between instances you can use the webPreferences.partition api in electron.

import Nightmare from 'nightmare';

nightmare = Nightmare(); // non persistent paritition by default
yield nightmare
  .evaluate(() => {
    window.localStorage.setItem('testing', 'This will not be persisted');
  })
  .end();

nightmare = Nightmare({
  webPreferences: {
    partition: 'persist: testing'
  }
});
yield nightmare
  .evaluate(() => {
    window.localStorage.setItem('testing', 'This is persisted for other instances with the same paritition name');
  })
  .end();

If you specify a null paritition then it will use the electron default behavior (persistent) or any string that starts with 'persist:' will persist under that partition name, any other string will result in in-memory only storage.

Usage

Installation

Nightmare is a Node.js module, so you'll need to have Node.js installed. Then you just need to npm install the module:

$ npm install --save nightmare

Execution

Nightmare is a node module that can be used in a Node.js script or module. Here's a simple script to open a web page:

import Nightmare from 'nightmare';

const nightmare = Nightmare();

nightmare.goto('http://cnn.com')
  .evaluate(() => {
    return document.title;
  })
  .end()
  .then((title) => {
    console.log(title);
  })

If you save this as cnn.js, you can run it on the command line like this:

npm install --save nightmare
node cnn.js

Common Execution Problems

Nightmare heavily relies on Electron for heavy lifting. And Electron in turn relies on several UI-focused dependencies (eg. libgtk+) which are often missing from server distros.

For help running nightmare on your server distro check out How to run nightmare on Amazon Linux and CentOS guide.

Debugging

There are three good ways to get more information about what's happening inside the headless browser:

  1. Use the DEBUG=* flag described below.
  2. Pass { show: true } to the nightmare constructor to have it create a visible, rendered window where you can watch what is happening.
  3. Listen for specific events.

To run the same file with debugging output, run it like this DEBUG=nightmare node cnn.js (on Windows use set DEBUG=nightmare & node cnn.js).

This will print out some additional information about what's going on:

nightmare queueing action "goto" +0ms
nightmare queueing action "evaluate" +4ms
Breaking News, U.S., World, Weather, Entertainment & Video News - CNN.com
Debug Flags

All nightmare messages

DEBUG=nightmare*

Only actions

DEBUG=nightmare:actions*

Only logs

DEBUG=nightmare:log*

Additional Resources

Tests

Automated tests for nightmare itself are run using Mocha and Chai, both of which will be installed via npm install. To run nightmare's tests, just run make test.

When the tests are done, you'll see something like this:

make test
  ․․․․․․․․․․․․․․․․․․
  18 passing (1m)

Note that if you are using xvfb, make test will automatically run the tests under an xvfb-run wrapper. If you are planning to run the tests headlessly without running xvfb first, set the HEADLESS environment variable to 0.

License (MIT)

WWWWWW||WWWWWW
 W W W||W W W
      ||
    ( OO )__________
     /  |           \
    /o o|    MIT     \
    \___/||_||__||_|| *
         || ||  || ||
        _||_|| _||_||
       (__|__|(__|__|

Copyright (c) 2015 Segment.io, Inc. mailto:friends@segment.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

changelog

3.0.1 / 2018-03-29

  • bump electron to fix #1424

3.0.0 / 2018-03-02

  • BREAKING: remove window.__nightmare.ipc to resolve the major security issues (#1390)
  • BREAKING: properly serialize error values (#1391)
  • added linting, formatting and a git pre-commit hook (#1386)
  • Added ability to specify the client certificate selected by electron (#1339)
  • adding selector to the timeout error in .wait() (#1381)
  • Pin Electron version (#1270)
  • Fix error on preload (#1247)
  • Add mouseout action to complement mouseover (#1238)
  • fix problems that are rejected when adding child actions with objects. (#1093)
  • Set mouse position for mouse events (#1077)
  • Repaired support for multiple timeouts in FrameManager (#945)

2.10.0 / 2017-02-23

  • Remove redundant docs for 'log' event from README
  • changed some var declarations to const
  • replace the 404 link with valid link
  • added Promise override tests
  • added docs for new Promise override features
  • added ability to override internal Promise library

2.9.1 / 2017-01-02

  • Minor touchups to key press documentation
  • Link to Electron documentation updated
  • Updates speed information on the readme
  • Swaps Yahoo example out for a faster DuckDuckGo example
  • Fixes an issue where nightmare may be undefined in the browser at injection time
  • Changes screenshot rendering to use debugger API instead of forcing a DOM change

2.9.0 / 2016-12-17

  • Prevents unload dialogs, allowing Nightmare to end gracefully
  • .end(fn) now uses .then() under the covers
  • Possibly breaking change: Nightmare will now default to using a non-persistent partition. Data between executions of Nightmare will no longer be saved.
  • Adds .mouseup() action
  • Fixes several typos/copy-paste errors in the readme, as well as clarifying error-first callbacks
  • Adds .path() to get the URL's route (as opposed to the fully-qualified URL)

2.8.1 / 2016-10-20

  • Fixes parsing issues with arguments to evaluate_now
  • Upgrades to Electron 1.4.4

2.8.0 / 2016-10-20

  • Fixes a missing semicolon in the first readme example
  • Fixes a reference error inside .wait() when using node --use_strict
  • Adds missing documentation for .mouseover()
  • Corrects a typo in the readme
  • Removes dependency on object-assign
  • Adds .halt() API to stop Nightmare execution immediately
  • Fixes blur exception when elements are removed by keyboard events
  • Possibly breaking change: Changes .evaluate() to allow for asynchronous execution. If the .evaluate()d function's arity is one less than the passed in parameters, it'll assume the last argument to the function is the callback. If the return value is a thenable, it'll call then() to wait for promise fulfillment. Otherwise, the call will behave synchronously as it does now.

2.7.0 / 2016-09-05

  • Adds .wait(element, timeout) to wait for whichever comes first
  • .end() will now end Electron gracefully instead of issuing a SIGKILL
  • Touches up readme for .end()

2.6.1 / 2016-08-08

  • Fixes treating provisional load failures as real load failures

2.6.0 / 2016-08-02

  • Makes the CircleCI badge an SVG
  • Adds an option for .type() to control time elapsed between keystrokes with typeInterval
  • Adds .cookies.clearAll() to clear all cookies
  • Fixes crashing if the Electron process is closed first
  • Adds pollInterval as an option to control the tick time for .wait()
  • Forces Nightmare to error on bad HTTP authentication
  • Fixes a crash by omitting event data due to circular references
  • Adds environment variable forwarding to the Electron process
  • Fixes openDevTools docs to be more explicit about detaching the devtools tray
  • Fixes the link to the preload script

2.5.3 / 2016-07-08

  • Adds better proxy information to the readme
  • Fixes a readme typo
  • Updates ipcRenderer usage for preload scripts in readme
  • Bumps Electron to version 1.2.5

2.5.2 / 2016-06-20

  • Fixes Referer header support
  • Removes timeout between keystrokes when using .type()
  • Checks instance existence when calling .end()
  • Adds a link to nightmare-examples
  • Changes yield to .then() in readme
  • Swaps did-finish-loading for did-stop-loading when waiting for page transitions
  • Adds optional loadTimeout for server responses that do not end

2.5.1 / 2016-06-07

  • Bumps Electron dependency to 1.2.1.
  • Removes a sender workaround
  • Moves the start of Electron from the constructor into the queue

2.5.0 / 2016-05-27

  • adds a timeout to .goto() such that pages that load the DOM but never finish are considered successful, otherwise failing, preventing a hang.
  • updates the example script and readme file for consistency.
  • reports with more helpful messages when the element does not exist when running .click(), .mousedown() and .mouseover().
  • .coookies.clear() with no arguments will clear all cookies for the current domain.
  • adds Node engine information to package and ensures CircleCI builds and tests against 4.x, 5.x and 6.x.
  • removes extranneous javascript event listeners upon execution completion or error.
  • adds .once() and .removeListener() for more complete Electron process event handling.

2.4.1 / 2016-05-19

  • Points invalid test URLs to the .tld domain
  • Switches javascript templates over to using template strings.
  • Adds better switch tests
  • Javascript gotos now only wait if the main frame is loading
  • Allows a Nightmare instance to use .catch() without a .then()
  • Fixes a deprecated IPC inclusion in tests
  • .goto() rejects with a helpful message when url is not provided

2.4.0 / 2016-05-05

  • adds call safety with IPC callbacks
  • adds .engineVersions() to get Electron and Chrome versions, as well as Nightmare.version
  • changes Yahoo example to use more robust selectors, adds .catch()
  • adds a check for runner arguments

2.3.4 / 2016-04-23

  • blurs text inputs when finished with .type() or .input(), including clearing selectors
  • now errors properly for non-existent selectors when using .type() and .input()
  • strips sender from Electron -> parent process forwarded events
  • improves test speed for dev tools
  • fixes .then() to comply with A+ promises
  • pipes Electron output to debug prefixed with electron:
  • cleans up several exception test cases using .should.be.rejected from chai-as-promised
  • upgrades to Electron 0.37.7
  • removes process event listeners when a Nightmare instance ends
  • fixes support for javascript: urls

2.3.3 / 2016-04-19

  • fixes .goto() failing when the page does not load
  • fixes deprecated Electron APIs
  • adds testing for deprecated API usage in Electron

2.3.2 / 2016-04-14

  • fixes the .wait(selector) comment
  • adds documentation about headers
  • adds an interim gitter badge
  • adds a unit test for openDevTools
  • bumps to electron 0.37.5
  • adds a wrapper to run unit tests when on CircleCI, when Xvfb is running, or the HEADLESS environment variable is set. Prevents Nightmare from hanging when running headlessly.
  • .evaluate() errors if a function to evaluate is not supplied

2.3.1 / 2016-04-11

  • fixes passing uncaught exceptions back to the default handler after cleanup
  • fixes overhead due to automatic subscription to frame data for screenshots
  • Adds unicode documentation for .type()

2.3.0 / 2016-04-02

  • extends .action() to include adding actions on the Electron process
  • adds a debugging message to inspect how Electron exited
  • ensures multiple instances of Nightmare do not use the same waitTimeout value
  • ensures cookies are not shared across tests
  • adds basic HTTP authentication
  • fixes console.log with injected/evaluated script
  • ensures screenshots match the currently rendered frame
  • adds ability to open and detach dev tools
  • removes the double-injection from .inject()
  • adds ability to save entire page as HTML

2.2.0 / 2016-02-16

  • .then() now returns a full promise instead of nightmare. update yahoo example.

2.1.6 / 2016-02-01

  • Fix failed wait with queued up functions
  • fix fullscreen switching (#434)

2.1.5 / 2016-02-01

  • add .insert(selector[, text]).
  • improve .type(selector[, text]) robustness.
  • bump electron and fix API updates.

2.1.4 / 2016-01-28

  • added debugging flags to README
  • Update use of electron APIs to kill deprecation warnings for 1.0
  • Implement dock option
  • added default waitTimout
  • page event listener fix

2.1.3 / 2016-01-18

  • added ability to uncheck
  • now properly fails with integer wait time
  • Added ability to return buffer from pdf
  • add ability to clear cookies
  • Added a documentation for .viewport(width, height)
  • Uncomment OS X dock hide
  • fix setting electron paths

2.1.2 / 2015-12-25

  • Support typing in non-strings
  • Support Chrome command line switches.
  • fix eventemitter leak message
  • Blur focussed on click. Fixes #400

2.1.1 / 2015-12-21

  • clears inputs on falsey/empty values

2.1.0 / 2015-12-17

  • BREAKING: changed page-error, page-alert, and page-log to console with types error, alert, log
  • BREAKING: fixed signature on nightmare.on('console', ...), to act more like console.log(...)

  • use native electron sendInputEvent for nightmare.type(...)

  • properly shutdown nightmare after certain tests and update formatting on the readme
  • add events for prompt, alert, confirm, and the other console events
  • update docs for preload script
  • support passing in a custom preload script
  • Update PDF Options
  • follow new BrowserWindow option naming
  • remove useless mocha opt
  • implement electronPath option
  • Fixed 'args is not defined' error for paths option

2.0.9 / 2015-12-09

  • add Nightmare.action(name, action|namespace) and nightmare.use(plugin)
  • bump dependencies
  • Add header() method, and optional headers param to goto()
  • "manipulation" fixture fixed to correctly test horizontal scrolling
  • Viewport size changed in the 'should set viewport' test (for test passing on small screen resolution).
  • prevent alerts from blocking
  • Add support to wait(fn) for passing arguments from node context to browser context, just like evaluate()
  • better cross-platform tests
  • add mousedown event
  • add nightmare.cookies.get(...) and nightmare.cookies.set(...) support
  • improve screenshot documentation
  • remove .only from buffered image test case
  • return a buffered image if no path is provided
  • Allow overriding Electron app paths
  • Update mocha-generators so tests run

2.0.8 / 2015-11-24

  • pointing to versioned Electron documentation
  • Use "did-stop-loading" event in "continue"
  • Fix menu sub-section URL in documentation
  • updating yahoo mocha example so it works with yahoo's changes, fixes #275
  • adding a more complete example, fixes #295
  • updating atom events links, fixes #312 and #258
  • set make test as the npm test target
  • log and error event clean up
  • Added license to package.json
  • replace co-mocha w/ mocha-generators
  • Allow for user-specified web-preferences options.
  • Add test case for 'type' The test case of 'type and click' doesn't ensure 'type' works
  • Remove old evaluate method, fix #257

2.0.7 / 2015-10-01

  • updated and clarified docs
  • fixed package.json description, thanks @tscanlin
  • better error handling for ipc, thanks @davidnaas

    2.0.6 / 2015-09-25

  • changing the tests to point to github to avoid the great firewall fix #249

  • Use node-integration for electron, fix scripts loading fix #242 #247
  • Remove after and util in test/index.js
  • adding windows debug hint

    2.0.5 / 2015-09-20

  • adding .useragent() support back, thanks @jefeweisen!

    2.0.4 / 2015-09-20

  • improving logging for screenshot, events and goto

    2.0.3 / 2015-09-19

  • improving test cleanup, thanks @fritx!

  • bumping electron from 0.32.2 to 0.33.0

    2.0.2 / 2015-09-13

  • improving tests for rendering

  • adding support for screenshot clip rect #107

    2.0.1 / 2015-09-13

  • updated package.json

  • credits to @matthewmueller!

2.0.0 / 2015-06-01

  • see #200 for details
  • added generator love
  • switched to electron to speed things up
  • many many thanks to @matthewmueller!

1.8.1 / 2015-04-27

  • Fix escaping of selectors in .wait(selector) thanks @thotypous
  • Updated Mocha link thanks @mortonfox

1.8.0 / 2015-03-23

  • handling phantom crashes more gracefully
  • fixing tests by using a local server and static fixtures
  • feat(docs): add google-oauth2 plugin
  • fixing links
  • clearer ToC and clearer evaluate docs from #89

1.7.0 / 2015-01-26

  • adding pdf ignore, fixing test timeout
  • adding new resourceRequestStarted event for executing in phantomjs context
  • Add scrollTo feature. Resolves #130.
  • Adds zoom feature. Resolves #136.
  • added error handling for requiring file extension in screenshot
  • added documentation for supported filetypes for .screenshot
  • add json parsing guard to test
  • adding link to tests for more examples
  • updating readme with clearer function lists and sections, and mocha test example
  • add readme for headers()
  • add tests for headers()
  • add headers method
  • upping timeouts
  • Add ability to save an A4 sized PDF
  • add check and select

1.6.5 / 2014-11-11

  • updating tests and fixing global port issue
  • Adding sequential test case
  • adding multiple clicks across multiple pages test

1.6.4 / 2014-11-10

  • fixing non-existent elem issue in .visible(), fixes #108

1.6.3 / 2014-11-09

  • bumping circleci test version and timeout
  • eliminating global phantom instance and state, fixes #104

1.6.2 / 2014-11-09

  • .type() now uses uses phantom's sendEvent to trigger keypress events. Fixes #81. (by @johntitus)

1.6.1 / 2014-11-09

  • bumping phantom to ~0.7.0, fixes #101
  • readme tweaks
  • adding resourceError event to docs

1.6.0 / 2014-11-02

  • adding timeout handling (by @johntitus)
  • cleaning up styles in tests, adding tests for timeout event

1.5.3 / 2014-11-02

  • Add ability to specify a custom PhantomJS path (by @kevva)

1.5.2 / 2014-11-02

  • updating readme to explain .on() before .goto()
  • fixing callbacks for .wait()
  • adding grep to makefile tests
  • adding check for file existence before file upload, fixes #11

1.5.1 / 2014-10-26

  • making clicks cancelable to allow for ajax forms

1.5.0 / 2014-10-22

  • adding docs and support for ssl, proxy and other cli args

1.4.0 / 2014-10-22

  • added .exists() (by @johntitus)
  • Added .visible(selector) (by @johntitus)
  • Added .authentication(user,password) (by @johntitus)

1.3.3 / 2014-10-20

  • fix for 'Option to run phantom without weak' (by @securingsincity)

1.3.2 / 2014-10-15

  • clarifying a readme example, see #55

1.3.1 / 2014-10-15

  • expanding the readme (by @johntitus)

1.3.0 / 2014-10-15

  • adding a on() action to handle phantom page events (by @johntitus)

1.2.0 / 2014-10-15

  • adding .forward() method with test (by @stevenmiller888)
  • adding .inject() action, test, and updated readme (by @johntitus)

1.1.1 / 2014-10-08

  • adding wait(selector) test and clojure fix, fixes #39
  • adding extraction readme example
  • adding caveat to viewport docs, fixes #33
  • updating readme example
  • Remove OSX .DS_Store file

1.1.0 / 2014-10-05

  • changing run structure to auto-terminate phantomjs instances
  • naming goBack to back

1.0.5 / 2014-09-30

  • added .goBack()

1.0.4 / 2014-05-12

  • contain zalgo

1.0.3 / 2014-05-12

  • cleaning up run based on ians feedback

1.0.2 / 2014-05-12

  • fixing concat in place
  • cleaning up naming, whitespace, structure.. thanks @ianstormtaylor!
  • fixing readme and history

1.0.1 / 2014-05-10

  • fixing queueing and .use() call order
  • Merge pull request #15 from queckezz/fix/use-queueing
  • fixing tests
  • fixing history
  • queue .use(). Closes #10

1.0.0 / 2014-05-10

  • renaming methods, fixes #18 and #19
  • Merge pull request #17 from queckezz/update/phantomjs-node
  • Merge pull request #16 from stevenschobert/master
  • update phantomjs-node for 0.11.x support
  • add instance option for phantomjs port

0.1.7 / 2014-04-14

  • Merge pull request #14 from queckezz/update/allow-no-args
  • allow no args and fix debug for .evaluate()
  • fixing history

0.1.6 / 2014-04-13

  • adding .url(), more debug()s and a test for .url()
  • fxiing histoyr

0.1.5 / 2014-04-12

  • fixing impatient to only apply to upload since it breaks wait
  • fixing history

0.1.4 / 2014-04-12

  • making callbacks impatient based on timeouts
  • fixing history

0.1.3 / 2014-04-12

  • fixing upload not having a callback
  • fixing history

0.1.2 / 2014-04-11

  • clarifying readme
  • adding refresh method and wait for fn on page refresh
  • reworking wait function to make room for a new wait overload
  • refactoring tests into sections
  • fixing history

0.1.1 / 2014-04-08

  • adding test to duplicate queue ordering issue, fixing issue, fixes #9
  • adding nightmare-swiftly plugin mention with docs
  • fixing history

0.1.0 / 2014-04-07

  • adding .use() to docs
  • Merge pull request #8 from segmentio/use-rewrite
  • adding test for .use() pluggability
  • changes .run() to .evaluate(), removes .error() and cleans up internal wrapping
  • fixing history

0.0.13 / 2014-04-07

  • Merge pull request #6 from segmentio/phantomjs-node
  • fixing done callback, fixing agent setting and adding tests. fixes #4, #2, #3.
  • fixing run callback hanging, fixes #3
  • experimenting with phantomjs-node, for #5
  • Merge branch 'master' of https://github.com/segmentio/nightmare
  • Update Readme.md

0.0.12 / 2014-04-06

  • adding .viewport() and .agent(), fixes #2

0.0.11 / 2014-04-06

  • making debug output consistent
  • consistent naming
  • fixing .wait() readme docs
  • fixing history

0.0.10 / 2014-04-06

  • adding .run() method with docs and test. fixes #1
  • Update Readme.md
  • fixing history

0.0.9 / 2014-04-05

  • adding more debug statements
  • fixing history

0.0.8 / 2014-04-05

  • updating readme for screen and options
  • fixing timeout and adding debug for .screen() method
  • fixing history

0.0.7 / 2014-04-05

  • setting viewport
  • fixing history

0.0.6 / 2014-04-05

  • adding better debug logs for page load detection
  • fixing history

0.0.5 / 2014-04-05

  • fixing history

0.0.4 / 2014-04-05

  • fixing main for require to work
  • fixing history

0.0.3 / 2014-04-05

  • fixing tests and getting screen working
  • fixing history again

0.0.2 / 2014-04-05

  • pkilling phantomjs more aggressively
  • fixing phantom singletons
  • fixing history.md

0.0.1 / 2014-04-05

  • updating readme
  • removing unneded circleci stuff
  • adding circle badge to readme
  • adding circle.yml
  • adding tests with lots of fixes everywhere
  • filling in remaining parts of api
  • filling in wait function
  • filling in lots of the first draft
  • adding new done method
  • blocks sync
  • mvoing
  • all before proceding
  • copyright
  • copy
  • adding more wait options
  • adding in scaffolding and readme outline