PageRenderTime 78ms CodeModel.GetById 17ms app.highlight 51ms RepoModel.GetById 1ms app.codeStats 1ms

/node_modules/nightmare/Readme.md

https://bitbucket.org/nicomee/martingale
Markdown | 948 lines | 654 code | 294 blank | 0 comment | 0 complexity | 3bc61ff9ec05af0ae8a1359b0092a7d2 MD5 | raw file
  1[![Build Status](https://img.shields.io/circleci/project/segmentio/nightmare/master.svg)](https://circleci.com/gh/segmentio/nightmare)
  2[![Join the chat at https://gitter.im/rosshinkley/nightmare](https://badges.gitter.im/rosshinkley/nightmare.svg)](https://gitter.im/rosshinkley/nightmare?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
  3
  4# Nightmare
  5
  6Nightmare is a high-level browser automation library from [Segment](https://segment.com).
  7
  8The 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.
  9
 10Under the covers it uses [Electron](http://electron.atom.io/), which is similar to [PhantomJS](http://phantomjs.org/) but roughly [twice as fast](https://github.com/segmentio/nightmare/issues/484#issuecomment-184519591) and more modern. 
 11
 12**We've implemented [many](https://github.com/segmentio/nightmare/issues/1388) of the security recommendations [outlined by Electron](https://github.com/electron/electron/blob/master/docs/tutorial/security.md) to try and keep you safe, but vulnerabilities may exist in Electron that may allow a malicious website to execute code on your company. Avoid visiting untrusted websites.**
 13
 14[Niffy](https://github.com/segmentio/niffy) is a perceptual diffing tool built on Nightmare. It helps you detect UI changes and bugs across releases of your web app.
 15
 16[Daydream](https://github.com/segmentio/daydream) is a complementary chrome extension built by [@stevenmiller888](https://github.com/stevenmiller888) that generates Nightmare scripts for you while you browse.
 17
 18Many thanks to [@matthewmueller](https://github.com/matthewmueller) and [@rosshinkley](https://github.com/rosshinkley) for their help on Nightmare.
 19
 20* [Examples](#examples)
 21  * [UI Testing Quick Start](https://segment.com/blog/ui-testing-with-nightmare/)
 22  * [Perceptual Diffing with Niffy & Nightmare](https://segment.com/blog/perceptual-diffing-with-niffy/)
 23* [API](#api)
 24  * [Set up an instance](#nightmareoptions)
 25  * [Interact with the page](#interact-with-the-page)
 26  * [Extract from the page](#extract-from-the-page)
 27  * [Cookies](#cookies)
 28  * [Proxies](#proxies)
 29  * [Promises](#promises)
 30  * [Extending Nightmare](#extending-nightmare)
 31* [Usage](#usage)
 32* [Debugging](#debugging)
 33* [Additional Resources](#additional-resources)
 34
 35## Examples
 36
 37Let's search on DuckDuckGo:
 38
 39```js
 40const Nightmare = require('nightmare')
 41const nightmare = Nightmare({ show: true })
 42
 43nightmare
 44  .goto('https://duckduckgo.com')
 45  .type('#search_form_input_homepage', 'github nightmare')
 46  .click('#search_button_homepage')
 47  .wait('#r1-0 a.result__a')
 48  .evaluate(() => document.querySelector('#r1-0 a.result__a').href)
 49  .end()
 50  .then(console.log)
 51  .catch(error => {
 52    console.error('Search failed:', error)
 53  })
 54```
 55
 56You can run this with:
 57
 58```shell
 59npm install --save nightmare
 60node example.js
 61```
 62
 63Or, let's run some mocha tests:
 64
 65```js
 66const Nightmare = require('nightmare')
 67const chai = require('chai')
 68const expect = chai.expect
 69
 70describe('test duckduckgo search results', () => {
 71  it('should find the nightmare github link first', function(done) {
 72    this.timeout('10s')
 73
 74    const nightmare = Nightmare()
 75    nightmare
 76      .goto('https://duckduckgo.com')
 77      .type('#search_form_input_homepage', 'github nightmare')
 78      .click('#search_button_homepage')
 79      .wait('#links .result__a')
 80      .evaluate(() => document.querySelector('#links .result__a').href)
 81      .end()
 82      .then(link => {
 83        expect(link).to.equal('https://github.com/segmentio/nightmare')
 84        done()
 85      })
 86  })
 87})
 88```
 89
 90You can see examples of every function [in the tests here](https://github.com/segmentio/nightmare/blob/master/test/index.js).
 91
 92To get started with UI Testing, check out this [quick start guide](https://segment.com/blog/ui-testing-with-nightmare).
 93
 94### To install dependencies
 95
 96```
 97npm install
 98```
 99
100### To run the mocha tests
101
102```
103npm test
104```
105
106### Node versions
107
108Nightmare is intended to be run on NodeJS 4.x or higher.
109
110## API
111
112#### Nightmare(options)
113
114Creates a new instance that can navigate around the web. The available options are [documented here](https://github.com/atom/electron/blob/master/docs/api/browser-window.md#new-browserwindowoptions), along with the following nightmare-specific options.
115
116##### waitTimeout (default: 30s)
117
118Throws an exception if the `.wait()` didn't return `true` within the set timeframe.
119
120```js
121const nightmare = Nightmare({
122  waitTimeout: 1000 // in ms
123})
124```
125
126##### gotoTimeout (default: 30s)
127
128Throws 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.
129
130```js
131const nightmare = Nightmare({
132  gotoTimeout: 1000 // in ms
133})
134```
135
136##### loadTimeout (default: infinite)
137
138Forces 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.
139
140```js
141const nightmare = Nightmare({
142  loadTimeout: 1000 // in ms
143})
144```
145
146##### executionTimeout (default: 30s)
147
148The maximum amount of time to wait for an `.evaluate()` statement to complete.
149
150```js
151const nightmare = Nightmare({
152  executionTimeout: 1000 // in ms
153})
154```
155
156##### paths
157
158The 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
159
160You can overwrite them in Nightmare by doing the following:
161
162```js
163const nightmare = Nightmare({
164  paths: {
165    userData: '/user/data'
166  }
167})
168```
169
170##### switches
171
172The command line switches used by the Chrome browser that are also supported by Electron. Here's a list of supported Chrome command line switches:
173https://github.com/atom/electron/blob/master/docs/api/chrome-command-line-switches.md
174
175```js
176const nightmare = Nightmare({
177  switches: {
178    'proxy-server': '1.2.3.4:5678',
179    'ignore-certificate-errors': true
180  }
181})
182```
183
184##### electronPath
185
186The 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.
187
188```js
189const nightmare = Nightmare({
190  electronPath: require('electron')
191})
192```
193
194##### dock (OS X)
195
196A boolean to optionally show the Electron icon in the dock (defaults to `false`). This is useful for testing purposes.
197
198```js
199const nightmare = Nightmare({
200  dock: true
201})
202```
203
204##### openDevTools
205
206Optionally 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()`](https://github.com/electron/electron/blob/master/docs/api/web-contents.md#contentsopendevtoolsoptions) to be handled. This is also useful for testing purposes. Note that this option is honored only if `show` is set to `true`.
207
208```js
209const nightmare = Nightmare({
210  openDevTools: {
211    mode: 'detach'
212  },
213  show: true
214})
215```
216
217##### typeInterval (default: 100ms)
218
219How long to wait between keystrokes when using `.type()`.
220
221```js
222const nightmare = Nightmare({
223  typeInterval: 20
224})
225```
226
227##### pollInterval (default: 250ms)
228
229How long to wait between checks for the `.wait()` condition to be successful.
230
231```js
232const nightmare = Nightmare({
233  pollInterval: 50 //in ms
234})
235```
236
237##### maxAuthRetries (default: 3)
238
239Defines the number of times to retry an authentication when set up with `.authenticate()`.
240
241```js
242const nightmare = Nightmare({
243  maxAuthRetries: 3
244})
245```
246
247#### certificateSubjectName
248
249A string to determine the client certificate selected by electron. If this options is set, the [`select-client-certificate`](https://github.com/electron/electron/blob/master/docs/api/app.md#event-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`](https://electronjs.org/docs/api/structures/certificate).
250
251```js
252const nightmare = Nightmare({
253  certificateSubjectName: 'tester'
254})
255```
256
257#### .engineVersions()
258
259Gets the versions for Electron and Chromium.
260
261#### .useragent(useragent)
262
263Sets the `useragent` used by electron.
264
265#### .authentication(user, password)
266
267Sets the `user` and `password` for accessing a web page using basic authentication. Be sure to set it before calling `.goto(url)`.
268
269#### .end()
270
271Completes 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:
272
273```js
274nightmare
275  .goto(someUrl)
276  .end(() => 'some value')
277  //prints "some value"
278  .then(console.log)
279```
280
281#### .halt(error, done)
282
283Clears 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.
284
285### Interact with the Page
286
287#### .goto(url[, headers])
288
289Loads the page at `url`. Optionally, a `headers` hash can be supplied to set headers on the `goto` request.
290
291When a page load is successful, `goto` returns an object with metadata about the page load, including:
292
293* `url`: The URL that was loaded
294* `code`: The HTTP status code (e.g. 200, 404, 500)
295* `method`: The HTTP method used (e.g. "GET", "POST")
296* `referrer`: The page that the window was displaying prior to this load or an empty string if this is the first page load.
297* `headers`: An object representing the response headers for the request as in `{header1-name: header1-value, header2-name: header2-value}`
298
299If the page load fails, the error will be an object with the following properties:
300
301* `message`: A string describing the type of error
302* `code`: The underlying error code describing what went wrong. Note this is NOT the HTTP status code. For possible values, see https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h
303* `details`: A string with additional details about the error. This may be null or an empty string.
304* `url`: The URL that failed to load
305
306Note 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.
307
308You can also adjust how long `goto` will wait before timing out by setting the [`gotoTimeout` option](#gototimeout-default-30s) on the Nightmare constructor.
309
310#### .back()
311
312Goes back to the previous page.
313
314#### .forward()
315
316Goes forward to the next page.
317
318#### .refresh()
319
320Refreshes the current page.
321
322#### .click(selector)
323
324Clicks the `selector` element once.
325
326#### .mousedown(selector)
327
328Mousedowns the `selector` element once.
329
330#### .mouseup(selector)
331
332Mouseups the `selector` element once.
333
334#### .mouseover(selector)
335
336Mouseovers the `selector` element once.
337
338#### .mouseout(selector)
339
340Mouseout the `selector` element once.
341
342#### .type(selector[, text])
343
344Enters the `text` provided into the `selector` element. Empty or falsey values provided for `text` will clear the selector's value.
345
346`.type()` mimics a user typing in a textbox and will emit the proper keyboard events.
347
348Key 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')`.
349
350> If you don't need the keyboard events, consider using `.insert()` instead as it will be faster and more robust.
351
352#### .insert(selector[, text])
353
354Similar to `.type()`, `.insert()` enters the `text` provided into the `selector` element. Empty or falsey values provided for `text` will clear the selector's value.
355
356`.insert()` is faster than `.type()` but does not trigger the keyboard events.
357
358#### .check(selector)
359
360Checks the `selector` checkbox element.
361
362#### .uncheck(selector)
363
364Unchecks the `selector` checkbox element.
365
366#### .select(selector, option)
367
368Changes the `selector` dropdown element to the option with attribute [value=`option`]
369
370#### .scrollTo(top, left)
371
372Scrolls the page to desired position. `top` and `left` are always relative to the top left corner of the document.
373
374#### .viewport(width, height)
375
376Sets the viewport size.
377
378#### .inject(type, file)
379
380Injects a local `file` onto the current page. The file `type` must be either `js` or `css`.
381
382#### .evaluate(fn[, arg1, arg2,...])
383
384Invokes `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:
385
386```js
387const selector = 'h1'
388nightmare
389  .evaluate(selector => {
390    // now we're executing inside the browser scope.
391    return document.querySelector(selector).innerText
392  }, selector) // <-- that's how you pass parameters from Node scope to browser scope
393  .then(text => {
394    // ...
395  })
396```
397
398Error-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:
399
400```js
401const selector = 'h1'
402nightmare
403  .evaluate((selector, done) => {
404    // now we're executing inside the browser scope.
405    setTimeout(
406      () => done(null, document.querySelector(selector).innerText),
407      2000
408    )
409  }, selector)
410  .then(text => {
411    // ...
412  })
413```
414
415Note 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.
416
417Promises 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:
418
419```js
420const selector = 'h1';
421nightmare
422  .evaluate((selector) => (
423    new Promise((resolve, reject) => {
424      setTimeout(() => resolve(document.querySelector(selector).innerText), 2000);
425    )}, selector)
426  )
427  .then((text) => {
428    // ...
429  })
430```
431
432#### .wait(ms)
433
434Waits for `ms` milliseconds e.g. `.wait(5000)`.
435
436#### .wait(selector)
437
438Waits until the element `selector` is present e.g. `.wait('#pay-button')`.
439
440#### .wait(fn[, arg1, arg2,...])
441
442Waits until the `fn` evaluated on the page with `arg1, arg2,...` returns `true`. All the `args` are optional. See `.evaluate()` for usage.
443
444#### .header(header, value)
445
446Adds a header override for all HTTP requests. If `header` is undefined, the header overrides will be reset.
447
448### Extract from the Page
449
450#### .exists(selector)
451
452Returns whether the selector exists or not on the page.
453
454#### .visible(selector)
455
456Returns whether the selector is visible or not.
457
458#### .on(event, callback)
459
460Captures page events with the callback. You have to call `.on()` before calling `.goto()`. Supported events are [documented here](http://electron.atom.io/docs/api/web-contents/#class-webcontents).
461
462##### Additional "page" events
463
464###### .on('page', function(type="error", message, stack))
465
466This 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.
467
468##### "page" events
469
470Listens for `window.addEventListener('error')`, `alert(...)`, `prompt(...)` & `confirm(...)`.
471
472###### .on('page', function(type="error", message, stack))
473
474Listens for top-level page errors. This will get triggered when an error is thrown on the page.
475
476###### .on('page', function(type="alert", message))
477
478Nightmare disables `window.alert` from popping up by default, but you can still listen for the contents of the alert dialog.
479
480###### .on('page', function(type="prompt", message, response))
481
482Nightmare 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.
483
484###### .on('page', function(type="confirm", message, response))
485
486Nightmare 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.
487
488###### .on('console', function(type [, arguments, ...]))
489
490`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`.
491
492#### .once(event, callback)
493
494Similar to `.on()`, but captures page events with the callback one time.
495
496#### .removeListener(event, callback)
497
498Removes a given listener callback for an event.
499
500#### .screenshot([path][, clip])
501
502Takes 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](https://github.com/atom/electron/blob/master/docs/api/browser-window.md#wincapturepagerect-callback)), the image will be clipped to the rectangle.
503
504#### .html(path, saveType)
505
506Saves the current page as html as files to disk at the given path. Save type options are [here](https://github.com/atom/electron/blob/master/docs/api/web-contents.md#webcontentssavepagefullpath-savetype-callback).
507
508#### .pdf(path, options)
509
510Saves a PDF to the specified `path`. Options are [here](https://github.com/electron/electron/blob/v1.4.4/docs/api/web-contents.md#contentsprinttopdfoptions-callback).
511
512#### .title()
513
514Returns the title of the current page.
515
516#### .url()
517
518Returns the url of the current page.
519
520#### .path()
521
522Returns the path name of the current page.
523
524### Cookies
525
526#### .cookies.get(name)
527
528Gets a cookie by it's `name`. The url will be the current url.
529
530#### .cookies.get(query)
531
532Queries 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:
533
534```js
535// get all google cookies that are secure
536// and have the path `/query`
537nightmare
538  .goto('http://google.com')
539  .cookies.get({
540    path: '/query',
541    secure: true
542  })
543  .then(cookies => {
544    // do something with the cookies
545  })
546```
547
548Available properties are documented here: https://github.com/atom/electron/blob/master/docs/api/session.md#sescookiesgetdetails-callback
549
550#### .cookies.get()
551
552Gets all the cookies for the current url. If you'd like get all cookies for all urls, use: `.get({ url: null })`.
553
554#### .cookies.set(name, value)
555
556Sets a cookie's `name` and `value`. This is the most basic form, and the url will be the current url.
557
558#### .cookies.set(cookie)
559
560Sets a `cookie`. If `cookie.url` is not set, it will set the cookie on the current url. Here's an example:
561
562```js
563nightmare
564  .goto('http://google.com')
565  .cookies.set({
566    name: 'token',
567    value: 'some token',
568    path: '/query',
569    secure: true
570  })
571  // ... other actions ...
572  .then(() => {
573    // ...
574  })
575```
576
577Available properties are documented here: https://github.com/atom/electron/blob/master/docs/api/session.md#sescookiessetdetails-callback
578
579#### .cookies.set(cookies)
580
581Sets 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.
582
583#### .cookies.clear([name])
584
585Clears a cookie for the current domain. If `name` is not specified, all cookies for the current domain will be cleared.
586
587```js
588nightmare
589  .goto('http://google.com')
590  .cookies.clear('SomeCookieName')
591  // ... other actions ...
592  .then(() => {
593    // ...
594  })
595```
596
597#### .cookies.clearAll()
598
599Clears all cookies for all domains.
600
601```js
602nightmare
603  .goto('http://google.com')
604  .cookies.clearAll()
605  // ... other actions ...
606  .then(() => {
607    //...
608  })
609```
610
611### Proxies
612
613Proxies are supported in Nightmare through [switches](#switches).
614
615If your proxy requires authentication you also need the [authentication](#authenticationuser-password) call.
616
617The following example not only demonstrates how to use proxies, but you can run it to test if your proxy connection is working:
618
619```js
620import Nightmare from 'nightmare';
621
622const proxyNightmare = Nightmare({
623  switches: {
624    'proxy-server': 'my_proxy_server.example.com:8080' // set the proxy server here ...
625  },
626  show: true
627});
628
629proxyNightmare
630  .authentication('proxyUsername', 'proxyPassword') // ... and authenticate here before `goto`
631  .goto('http://www.ipchicken.com')
632  .evaluate(() => {
633    return document.querySelector('b').innerText.replace(/[^\d\.]/g, '');
634  })
635  .end()
636  .then((ip) => { // This will log the Proxy's IP
637    console.log('proxy IP:', ip);
638  });
639
640// The rest is just normal Nightmare to get your local IP
641const regularNightmare = Nightmare({ show: true });
642
643regularNightmare
644  .goto('http://www.ipchicken.com')
645  .evaluate(() =>
646    document.querySelector('b').innerText.replace(/[^\d\.]/g, '');
647  )
648  .end()
649  .then((ip) => { // This will log the your local IP
650    console.log('local IP:', ip);
651  });
652```
653
654### Promises
655
656By default, Nightmare uses default native ES6 promises. You can plug in your favorite [ES6-style promises library](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) like [bluebird](https://www.npmjs.com/package/bluebird) or [q](https://www.npmjs.com/package/q) for convenience!
657
658Here's an example:
659
660```js
661var Nightmare = require('nightmare')
662
663Nightmare.Promise = require('bluebird')
664// OR:
665Nightmare.Promise = require('q').Promise
666```
667
668You can also specify a custom Promise library per-instance with the `Promise` constructor option like so:
669
670```js
671var Nightmare = require('nightmare')
672
673var es6Nightmare = Nightmare()
674var bluebirdNightmare = Nightmare({
675  Promise: require('bluebird')
676})
677
678var es6Promise = es6Nightmare
679  .goto('https://github.com/segmentio/nightmare')
680  .then()
681var bluebirdPromise = bluebirdNightmare
682  .goto('https://github.com/segmentio/nightmare')
683  .then()
684
685es6Promise.isFulfilled() // throws: `TypeError: es6EndPromise.isFulfilled is not a function`
686bluebirdPromise.isFulfilled() // returns: `true | false`
687```
688
689### Extending Nightmare
690
691#### Nightmare.action(name, [electronAction|electronNamespace], action|namespace)
692
693You can add your own custom actions to the Nightmare prototype. Here's an example:
694
695```js
696Nightmare.action('size', function(done) {
697  this.evaluate_now(() => {
698    const w = Math.max(
699      document.documentElement.clientWidth,
700      window.innerWidth || 0
701    )
702    const h = Math.max(
703      document.documentElement.clientHeight,
704      window.innerHeight || 0
705    )
706    return {
707      height: h,
708      width: w
709    }
710  }, done)
711})
712
713Nightmare()
714  .goto('http://cnn.com')
715  .size()
716  .then(size => {
717    //... do something with the size information
718  })
719```
720
721> Remember, this is attached to the static class `Nightmare`, not the instance.
722
723You'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.
724
725An 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.
726
727We 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:
728
729```js
730Nightmare.action('style', {
731  background(done) {
732    this.evaluate_now(
733      () => window.getComputedStyle(document.body, null).backgroundColor,
734      done
735    )
736  }
737})
738
739Nightmare()
740  .goto('http://google.com')
741  .style.background()
742  .then(background => {
743    // ... do something interesting with background
744  })
745```
746
747You 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:
748
749```javascript
750Nightmare.action(
751  'clearCache',
752  (name, options, parent, win, renderer, done) => {
753    parent.respondTo('clearCache', done => {
754      win.webContents.session.clearCache(done)
755    })
756    done()
757  },
758  function(done) {
759    this.child.call('clearCache', done)
760  }
761)
762
763Nightmare()
764  .clearCache()
765  .goto('http://example.org')
766  //... more actions ...
767  .then(() => {
768    // ...
769  })
770```
771
772...would clear the browser’s cache before navigating to `example.org`.
773
774See [this document](https://github.com/rosshinkley/nightmare-examples/blob/master/docs/beginner/action.md) for more details on creating custom actions.
775
776#### .use(plugin)
777
778`nightmare.use` is useful for reusing a set of tasks on an instance. Check out [nightmare-swiftly](https://github.com/segmentio/nightmare-swiftly) for some examples.
779
780#### Custom preload script
781
782If you need to do something custom when you first load the window environment, you
783can specify a custom preload script. Here's how you do that:
784
785```js
786import path from 'path'
787
788const nightmare = Nightmare({
789  webPreferences: {
790    preload: path.resolve('custom-script.js')
791    //alternative: preload: "absolute/path/to/custom-script.js"
792  }
793})
794```
795
796The only requirement for that script is that you'll need the following prelude:
797
798```js
799window.__nightmare = {}
800__nightmare.ipc = require('electron').ipcRenderer
801```
802
803To benefit of all of nightmare's feedback from the browser, you can instead copy the contents of nightmare's [preload script](lib/preload.js).
804
805#### Storage Persistence between nightmare instances
806
807By 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](http://electron.atom.io/docs/api/browser-window/#new-browserwindowoptions) api in electron.
808
809```js
810import Nightmare from 'nightmare';
811
812nightmare = Nightmare(); // non persistent paritition by default
813yield nightmare
814  .evaluate(() => {
815    window.localStorage.setItem('testing', 'This will not be persisted');
816  })
817  .end();
818
819nightmare = Nightmare({
820  webPreferences: {
821    partition: 'persist: testing'
822  }
823});
824yield nightmare
825  .evaluate(() => {
826    window.localStorage.setItem('testing', 'This is persisted for other instances with the same paritition name');
827  })
828  .end();
829```
830
831If 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.
832
833## Usage
834
835#### Installation
836
837Nightmare is a Node.js module, so you'll need to [have Node.js installed](http://nodejs.org/). Then you just need to `npm install` the module:
838
839```bash
840$ npm install --save nightmare
841```
842
843#### Execution
844
845Nightmare 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:
846
847```js
848import Nightmare from 'nightmare';
849
850const nightmare = Nightmare();
851
852nightmare.goto('http://cnn.com')
853  .evaluate(() => {
854    return document.title;
855  })
856  .end()
857  .then((title) => {
858    console.log(title);
859  })
860```
861
862If you save this as `cnn.js`, you can run it on the command line like this:
863
864```bash
865npm install --save nightmare
866node cnn.js
867```
868
869#### Common Execution Problems
870
871Nightmare heavily relies on [Electron](http://electron.atom.io/) for heavy lifting. And Electron in turn relies on several UI-focused dependencies (eg. libgtk+) which are often missing from server distros.
872
873For help running nightmare on your server distro check out [How to run nightmare on Amazon Linux and CentOS](https://gist.github.com/dimkir/f4afde77366ff041b66d2252b45a13db) guide.
874
875#### Debugging
876
877There are three good ways to get more information about what's happening inside the headless browser:
878
8791. Use the `DEBUG=*` flag described below.
8802. Pass `{ show: true }` to the [nightmare constructor](#nightmareoptions) to have it create a visible, rendered window where you can watch what is happening.
8813. Listen for [specific events](#onevent-callback).
882
883To 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`).
884
885This will print out some additional information about what's going on:
886
887```bash
888nightmare queueing action "goto" +0ms
889nightmare queueing action "evaluate" +4ms
890Breaking News, U.S., World, Weather, Entertainment & Video News - CNN.com
891```
892
893##### Debug Flags
894
895All nightmare messages
896
897`DEBUG=nightmare*`
898
899Only actions
900
901`DEBUG=nightmare:actions*`
902
903Only logs
904
905`DEBUG=nightmare:log*`
906
907## Additional Resources
908
909* [Ross Hinkley's Nightmare Examples](https://github.com/rosshinkley/nightmare-examples) is a great resource for setting up nightmare, learning about custom actions, and avoiding common pitfalls.
910
911* [Nightmarishly good scraping](https://hackernoon.com/nightmarishly-good-scraping-with-nightmare-js-and-async-await-b7b20a38438f) is a great tutorial by [Ændrew Rininsland](https://twitter.com/@aendrew) on getting up & running with Nightmare using real-life data.
912
913## Tests
914
915Automated tests for nightmare itself are run using [Mocha](http://mochajs.org/) and Chai, both of which will be installed via `npm install`. To run nightmare's tests, just run `make test`.
916
917When the tests are done, you'll see something like this:
918
919```bash
920make test
921  ․․․․․․․․․․․․․․․․․․
922  18 passing (1m)
923```
924
925Note 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`.
926
927## License (MIT)
928
929```
930WWWWWW||WWWWWW
931 W W W||W W W
932      ||
933    ( OO )__________
934     /  |           \
935    /o o|    MIT     \
936    \___/||_||__||_|| *
937         || ||  || ||
938        _||_|| _||_||
939       (__|__|(__|__|
940```
941
942Copyright (c) 2015 Segment.io, Inc. <mailto:friends@segment.com>
943
944Permission 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:
945
946The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
947
948THE 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.