{"_id":"@dfrankland/nightmare","_rev":"3-28aaa620593672dfc45acb168273e10b","name":"@dfrankland/nightmare","description":"A high-level browser automation library.","dist-tags":{"latest":"2.8.1"},"versions":{"2.8.1":{"name":"@dfrankland/nightmare","version":"2.8.1","license":"MIT","main":"lib/nightmare.js","scripts":{"test":"make test"},"repository":{"type":"git","url":"git+https://github.com/segmentio/nightmare.git"},"author":{"name":"Segment"},"keywords":["nightmare","electron"],"description":"A high-level browser automation library.","dependencies":{"debug":"^2.2.0","deep-defaults":"^1.0.3","defaults":"^1.0.2","electron":"^1.4.4","enqueue":"^1.0.2","function-source":"^0.1.0","jsesc":"^0.5.0","minstache":"^1.2.0","mkdirp":"^0.5.1","once":"^1.3.3","rimraf":"^2.4.3","sliced":"1.0.1","split2":"^2.0.1"},"devDependencies":{"basic-auth":"^1.0.3","basic-auth-connect":"^1.0.0","chai":"^3.4.1","chai-as-promised":"^5.3.0","express":"^4.13.3","mocha":"^2.3.0","mocha-generators":"^1.2.0","multer":"1.1.0","pngjs":"^2.2.0","serve-static":"^1.10.0","split":"^1.0.0"},"engines":{"node":">=4.0.0"},"gitHead":"3e6978794ac399ee323e0e11a80791811056dad4","bugs":{"url":"https://github.com/segmentio/nightmare/issues"},"homepage":"https://github.com/segmentio/nightmare#readme","_id":"@dfrankland/nightmare@2.8.1","_shasum":"8ad3a63afd6527d07b6e6796118790e998aa2efe","_from":".","_npmVersion":"3.10.9","_nodeVersion":"6.3.1","_npmUser":{"name":"dfrankland","email":"dylan@frankland.io"},"dist":{"shasum":"8ad3a63afd6527d07b6e6796118790e998aa2efe","tarball":"https://registry.npmjs.org/@dfrankland/nightmare/-/nightmare-2.8.1.tgz","integrity":"sha512-VHRTC5VNSHq3MDiRPDlGYH2zqfSi/4IRmbq/j1C197wNmIJNHgI7OAFV4mf11834y4WgMXZ9guEaTQE9isIm+A==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAdNDXbaNvvjBNegaJAE8eFNAfQUULD1aaAhQEJ81+GGAiBNMxxzKhPQAeXvoEEpxU2f0WwzTTHfqOrtkf+Fti1hNQ=="}]},"maintainers":[{"name":"dfrankland","email":"dylan@frankland.io"}],"_npmOperationalInternal":{"host":"packages-18-east.internal.npmjs.com","tmp":"tmp/nightmare-2.8.1.tgz_1477793109090_0.6912813775707036"}}},"readme":"[![Build Status](https://img.shields.io/circleci/project/segmentio/nightmare/master.svg)](https://circleci.com/gh/segmentio/nightmare)\n[![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)\n\n# Nightmare\n\nNightmare is a high-level browser automation library.\n\nThe goal is to expose just a few simple methods, and have an API that feels synchronous for each block of scripting, rather than deeply nested callbacks. It's designed for automating tasks across sites that don't have APIs.\n\nUnder the covers it uses [Electron](http://electron.atom.io/), which is similar to [PhantomJS](http://phantomjs.org/) but faster and more modern.\n\n[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.\n\nMany thanks to [@matthewmueller](https://github.com/matthewmueller) and [@rosshinkley](https://github.com/rosshinkley) for their help on Nightmare.\n\n* [Examples](#examples)\n* [API](#api)\n  - [Set up an instance](#nightmareoptions)\n  - [Interact with the page](#interact-with-the-page)\n  - [Extract from the page](#extract-from-the-page)\n  - [Cookies](#cookies)\n  - [Proxies](#proxies)\n  - [Extending Nightmare](#extending-nightmare)\n* [Usage](#usage)\n* [Debugging](#debugging)\n* [Supplementary Examples and Documentation](https://github.com/rosshinkley/nightmare-examples)\n\n## Examples\n\nLet's search on Yahoo:\n\n```js\nvar Nightmare = require('nightmare');\nvar nightmare = Nightmare({ show: true });\n\nnightmare\n  .goto('http://yahoo.com')\n  .type('form[action*=\"/search\"] [name=p]', 'github nightmare')\n  .click('form[action*=\"/search\"] [type=submit]')\n  .wait('#main')\n  .evaluate(function () {\n    return document.querySelector('#main .searchCenterMiddle li a').href\n  })\n  .end()\n  .then(function (result) {\n    console.log(result)\n  })\n  .catch(function (error) {\n    console.error('Search failed:', error);\n  });\n```\n\nYou can run this with:\n\n```shell\nnpm install nightmare\nnode example.js\n```\n\nOr, let's run some mocha tests:\n\n```js\nvar Nightmare = require('nightmare');\nvar expect = require('chai').expect; // jshint ignore:line\n\ndescribe('test yahoo search results', function() {\n  it('should find the nightmare github link first', function(done) {\n    var nightmare = Nightmare()\n    nightmare\n      .goto('http://yahoo.com')\n      .type('form[action*=\"/search\"] [name=p]', 'github nightmare')\n      .click('form[action*=\"/search\"] [type=submit]')\n      .wait('#main')\n      .evaluate(function () {\n        return document.querySelector('#main .searchCenterMiddle li a').href\n      })\n      .end()\n      .then(function(link) {\n        expect(link).to.equal('https://github.com/segmentio/nightmare');\n        done();\n      })\n  });\n});\n```\n\nYou can see examples of every function [in the tests here](https://github.com/segmentio/nightmare/blob/master/test/index.js).\n\nPlease note that the examples are using the [mocha-generators](https://www.npmjs.com/package/mocha-generators)\npackage for Mocha, which enables the support for generators.\n\n### To install dependencies\n\n    npm install\n\n### To run the mocha tests\n\n    npm test\n\n### Node versions\n\nNightmare is intended to be run on NodeJS 4.x or higher.\n\n## API\n\n#### Nightmare(options)\nCreate 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.\n\n#### Nightmare.version\nReturns the version of Nightmare.\n\n##### waitTimeout (default: 30s)\nThis will throw an exception if the `.wait()` didn't return `true` within the set timeframe.\n\n```js\nvar nightmare = Nightmare({\n  waitTimeout: 1000 // in ms\n});\n```\n\n##### gotoTimeout (default: 30s)\nThis will throw 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.\n\n```js\nvar nightmare = Nightmare({\n  gotoTimeout: 1000 // in ms\n});\n```\n\n##### loadTimeout (default: infinite)\nThis will force 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.\n\n```js\nvar nightmare = Nightmare({\n  loadTimeout: 1000 // in ms\n});\n```\n##### executionTimeout (default: 30s)\nThe maxiumum amount of time to wait for an `.evaluate()` statement to complete.\n\n```js\nvar nightmare = Nightmare({\n  executionTimeout: 1000 // in ms\n});\n```\n\n##### paths\nThe 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\n\nYou can overwrite them in Nightmare by doing the following:\n\n```js\nvar nightmare = Nightmare({\n  paths: {\n    userData: '/user/data'\n  }\n});\n```\n\n##### switches\nThe command line switches used by the Chrome browser that are also supported by Electron. Here's a list of supported Chrome command line switches:\nhttps://github.com/atom/electron/blob/master/docs/api/chrome-command-line-switches.md\n\n```js\nvar nightmare = Nightmare({\n  switches: {\n    'proxy-server': '1.2.3.4:5678',\n    'ignore-certificate-errors': true\n  }\n});\n```\n\n##### electronPath\nThe path to prebuilt Electron binary.  This is useful for testing on different version Electron.  Note that Nightmare only supports the version this package depending on.  Please use this option at your own risk.\n\n```js\nvar nightmare = Nightmare({\n  electronPath: require('electron')\n});\n```\n\n##### dock (OS X)\nA boolean to optionally show the Electron icon in the dock (defaults to `false`).  This is useful for testing purposes.\n\n```js\nvar nightmare = Nightmare({\n  dock: true\n});\n```\n\n##### openDevTools\nOptionally show 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`.\n\n```js\nvar nightmare = Nightmare({\n  openDevTools: {\n    mode: 'detach'\n  },\n  show: true\n});\n```\n\n##### typeInterval (default: 100ms)\nHow long to wait between keystrokes when using `.type()`.\n\n```js\nvar nightmare = Nightmare({\n  typeInterval: 20\n});\n```\n\n##### pollInterval (default: 250ms)\nHow long to wait between checks for the `.wait()` condition to be successful.\n\n```js\nvar nightmare = Nightmare({\n  pollInterval: 50 //in ms\n});\n```\n\n##### maxAuthRetries (default: 3)\nDefines the number of times to retry an authentication when set up with `.authenticate()`.\n```js\nvar nightmare = Nightmare({\n  maxAuthRetries: 3\n});\n```\n\n#### .engineVersions()\nGets the versions for Electron and Chromium.\n\n#### .useragent(useragent)\nSet the `useragent` used by electron.\n\n#### .authentication(user, password)\nSet the `user` and `password` for accessing a web page using basic authentication. Be sure to set it before calling `.goto(url)`.\n\n#### .end()\nComplete 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.\n\n#### .halt(error, done)\nClears 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.\n\n### Interact with the Page\n\n#### .goto(url[, headers])\nLoad the page at `url`.  Optionally, a `headers` hash can be supplied to set headers on the `goto` request.\n\nWhen a page load is successful, `goto` returns an object with metadata about the page load, including:\n\n- `url`: The URL that was loaded\n- `code`: The HTTP status code (e.g. 200, 404, 500)\n- `method`: The HTTP method used (e.g. \"GET\", \"POST\")\n- `referrer`: The page that the window was displaying prior to this load or an empty string if this is the first page load.\n- `headers`: An object representing the response headers for the request as in `{header1-name: header1-value, header2-name: header2-value}`\n\nIf the page load fails, the error will be an object with the following properties:\n\n- `message`: A string describing the type of error\n- `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\n- `details`: A string with additional details about the error. This may be null or an empty string.\n- `url`: The URL that failed to load\n\nNote 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.\n\nYou can also adjust how long `goto` will wait before timing out by setting the [`gotoTimeout` option](#gototimeout-default-30s) on the Nightmare constructor.\n\n#### .back()\nGo back to the previous page.\n\n#### .forward()\nGo forward to the next page.\n\n#### .refresh()\nRefresh the current page.\n\n#### .click(selector)\nClicks the `selector` element once.\n\n#### .mousedown(selector)\nMousedown the `selector` element once.\n\n#### .mouseup(selector)\nMouseup the `selector` element once.\n\n#### .mouseover(selector)\nMouseover the `selector` element once.\n\n#### .type(selector[, text])\nEnters the `text` provided into the `selector` element.  Empty or falsey values provided for `text` will clear the selector's value.\n\n`.type()` mimics a user typing in a textbox and will emit the proper keyboard events\n\nKey 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('document', '\\u000d')`.\n\n> If you don't need the keyboard events, consider using `.insert()` instead as it will be faster and more robust.\n\n#### .insert(selector[, text])\nSimilar to `.type()`. `.insert()` enters the `text` provided into the `selector` element.  Empty or falsey values provided for `text` will clear the selector's value.\n\n`.insert()` is faster than `.type()` but does not trigger the keyboard events.\n\n#### .check(selector)\nchecks the `selector` checkbox element.\n\n#### .uncheck(selector)\nunchecks the `selector` checkbox element.\n\n#### .select(selector, option)\nChanges the `selector` dropdown element to the option with attribute [value=`option`]\n\n#### .scrollTo(top, left)\nScrolls the page to desired position. `top` and `left` are always relative to the top left corner of the document.\n\n#### .viewport(width, height)\n\nSet the viewport size.\n\n#### .inject(type, file)\nInject a local `file` onto the current page. The file `type` must be either `js` or `css`.\n\n#### .evaluate(fn[, arg1, arg2,...])\nInvokes `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:\n\n```js\nvar selector = 'h1';\nnightmare\n  .evaluate(function (selector) {\n    // now we're executing inside the browser scope.\n    return document.querySelector(selector).innerText;\n   }, selector) // <-- that's how you pass parameters from Node scope to browser scope\n  .then(function(text) {\n    // ...\n  })\n```\n\nCallbacks 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:\n\n```js\nvar selector = 'h1';\nnightmare\n  .evaluate(function (selector, done) {\n    // now we're executing inside the browser scope.\n    setTimeout(() => done(null, document.querySelector(selector).innerText), 2000);\n   }, selector)\n  .then(function(text) {\n    // ...\n  })\n```\nNote that callbacks support only one value argument.  Ultimately, the callback will get wrapped in a native Promise and only be able to resolve a single value.\n\nPromises 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:\n\n```js\nvar selector = 'h1';\nnightmare\n  .evaluate(function (selector, done) {\n      return new Promise((resolve, reject) => {\n        setTimeout(() => resolve(document.querySelector(selector).innerText), 2000);\n   }, selector)\n  .then(function(text) {\n    // ...\n  })\n```\n\n#### .wait(ms)\nWait for `ms` milliseconds e.g. `.wait(5000)`\n\n#### .wait(selector)\nWait until the element `selector` is present e.g. `.wait('#pay-button')`\n\n#### .wait(fn[, arg1, arg2,...])\nWait until the `fn` evaluated on the page with `arg1, arg2,...` returns `true`. All the `args` are optional. See `.evaluate()` for usage.\n\n#### .header([header, value])\nAdd a header override for all HTTP requests.  If `header` is undefined, the header overrides will be reset.\n\n### Extract from the Page\n\n#### .exists(selector)\nReturns whether the selector exists or not on the page.\n\n#### .visible(selector)\nReturns whether the selector is visible or not\n\n#### .on(event, callback)\nCapture page events with the callback. You have to call `.on()` before calling `.goto()`. Supported events are [documented here](http://electron.atom.io/docs/v0.30.0/api/browser-window/#class-webcontents).\n\n##### Additional \"page\" events\n\n###### .on('page', function(type=\"error\", message, stack))\nThis 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.\n\n##### \"page\" events\n\nListen for `window.addEventListener('error')`, `alert(...)`, `prompt(...)` & `confirm(...)`.\n\n###### .on('page', function(type=\"error\", message, stack))\n\nListen for top-level page errors. This will get triggered when an error is thrown on the page.\n\n###### .on('page', function(type=\"alert\", message))\n\nNightmare disables `window.alert` from popping up by default, but you can still listen for the contents of the alert dialog.\n\n###### .on('page', function(type=\"prompt\", message, response))\n\nNightmare 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.\n\n###### .on('page', function(type=\"confirm\", message, response))\n\nNightmare 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.\n\n###### .on('console', function(type [, arguments, ...]))\n\n`type` will be either `log`, `warn` or `error` and `arguments` are what gets passed from the console.\n\n##### Additional \"console\" events\n\nListen for `console.log(...)`, `console.warn(...)`, and `console.error(...)`.\n\n###### .on('console', function(type [, arguments, ...]))\n\n`type` will be either `log`, `warn` or `error` and `arguments` are what gets passed from the console.\n\n###### .on('console', function(type, errorMessage, errorStack))\nThis event is triggered if `console.log` is used on the page. But this event is not triggered if the injected javascript code (e.g. via `.evaluate()`) is using `console.log`.\n\n#### .once(event, callback)\nSimilar to `.on()`, but captures page events with the callback one time.\n\n#### .removeListener(event, callback)\nRemoves a given listener callback for an event.\n\n#### .screenshot([path][, clip])\nTakes 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.\n\n#### .html(path, saveType)\nSave 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).\n\n#### .pdf(path, options)\nSaves a PDF to the specified `path`. Options are [here](https://github.com/atom/electron/blob/v0.35.2/docs/api/web-contents.md#webcontentsprinttopdfoptions-callback).\n\n#### .title()\nReturns the title of the current page.\n\n#### .url()\nReturns the url of the current page.\n\n### Cookies\n\n#### .cookies.get(name)\n\nGet a cookie by it's `name`. The url will be the current url.\n\n#### .cookies.get(query)\n\nQuery 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:\n\n```js\n// get all google cookies that are secure\n// and have the path `/query`\nnightmare\n  .goto('http://google.com')\n  .cookies.get({\n    path: '/query',\n    secure: true\n  })\n  .then(function(cookies) {\n    // do something with the cookies\n  })\n```\n\nAvailable properties are documented here: https://github.com/atom/electron/blob/master/docs/api/session.md#sescookiesgetdetails-callback\n\n#### .cookies.get()\n\nGet all the cookies for the current url. If you'd like get all cookies for all urls, use: `.get({ url: null })`.\n\n#### .cookies.set(name, value)\n\nSet a cookie's `name` and `value`. Most basic form, the url will be the current url.\n\n#### .cookies.set(cookie)\n\nSet a `cookie`. If `cookie.url` is not set, it will set the cookie on the current url. Here's an example:\n\n```js\nnightmare\n  .goto('http://google.com')\n  .cookies.set({\n    name: 'token',\n    value: 'some token',\n    path: '/query',\n    secure: true\n  })\n  // ... other actions ...\n  .then(function() {\n    // ...\n  })\n```\n\nAvailable properties are documented here:  https://github.com/atom/electron/blob/master/docs/api/session.md#sescookiessetdetails-callback\n\n#### .cookies.set(cookies)\n\nSet 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.\n\n#### .cookies.clear([name])\n\nClear a cookie for the current domain.  If `name` is not specified, all cookies for the current domain will be cleared.\n\n```js\nnightmare\n  .goto('http://google.com')\n  .cookies.clear('SomeCookieName')\n  // ... other actions ...\n  .then(function() {\n    // ...\n  })\n```\n\n#### .cookies.clearAll()\n\nClears all cookies for all domains.\n\n```js\nnightmare\n  .goto('http://google.com')\n  .cookies.clearAll()\n  // ... other actions ...\n  .then(function() {\n    //...\n  });\n```\n\n### Proxies\n\nProxies are supported in Nightmare through [switches](#switches).\n\nIf your proxy requires authentication you also need the [authentication](#authenticationuser-password) call.\n\nThe following example not only demonstrates how to use proxies, but you can run it to test if your proxy connection is working:\n\n```js\nvar Nightmare = require('nightmare');\n\nvar proxyNightmare = Nightmare({\n  switches: {\n    'proxy-server': 'my_proxy_server.example.com:8080' // set the proxy server here ...\n  },\n  show: true\n});\n\nproxyNightmare\n  .authentication('proxyUsername', 'proxyPassword') // ... and authenticate here before `goto`\n  .goto('http://www.ipchicken.com')\n  .evaluate(function() {\n    return document.querySelector('b').innerText.replace(/[^\\d\\.]/g, '');\n  })\n  .end()\n  .then(function(ip) { // This will log the Proxy's IP\n    console.log('proxy IP:', ip);\n  });\n\n// The rest is just normal Nightmare to get your local IP\nvar regularNightmare = Nightmare({ show: true });\n\nregularNightmare\n  .goto('http://www.ipchicken.com')\n  .evaluate(function() {\n    return document.querySelector('b').innerText.replace(/[^\\d\\.]/g, '');\n  })\n  .end()\n  .then(function(ip) { // This will log the your local IP\n    console.log('local IP:', ip);\n  });\n```\n\n### Extending Nightmare\n\n#### Nightmare.action(name, [electronAction|electronNamespace], action|namespace)\n\nYou can add your own custom actions to the Nightmare prototype. Here's an example:\n\n```js\nNightmare.action('size', function (done) {\n  this.evaluate_now(function() {\n    var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)\n    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)\n    return {\n      height: h,\n      width: w\n    }\n  }, done)\n})\n\nNightmare()\n  .goto('http://cnn.com')\n  .size()\n  .then(function(size) {\n    //... do something with the size information\n  });\n```\n\n> Remember, this is attached to the static class `Nightmare`, not the instance.\n\nYou'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.\n\nAn 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.\n\nWe 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:\n\n```js\nNightmare.action('style', {\n  background: function (done) {\n    this.evaluate_now(function () {\n      return window.getComputedStyle(document.body, null).backgroundColor\n    }, done)\n  }\n})\n\nnightmare()\n  .goto('http://google.com')\n  .style.background()\n  .then(function(background) {\n    // ... do something interesting with background  \n  })\n```\n\nYou 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:\n\n```javascript\nNightmare.action('clearCache',\n  function(name, options, parent, win, renderer, done) {\n    parent.respondTo('clearCache', function(done) {\n      win.webContents.session.clearCache(done);\n    });\n    done();\n  },\n  function(message, done) {\n    this.child.call('clearCache', done);\n  });\n\nNightmare()\n  .clearCache()\n  .goto('http://example.org')\n  //... more actions ...\n  .then(function() {\n    // ...\n  });\n```\n\n...would clear the browser’s cache before navigating to `example.org`.\n\n#### .use(plugin)\n\n`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.\n\n#### Custom preload script\n\nIf you need to do something custom when you first load the window environment, you\ncan specify a custom preload script. Here's how you do that:\n\n```js\nconst path = require('path');\n\nvar nightmare = Nightmare({\n  webPreferences: {\n    preload: path.resolve(\"custom-script.js\")\n    //alternative: preload: \"absolute/path/to/custom-script.js\"\n  }\n})\n```\n\nThe only requirement for that script is that you'll need the following prelude:\n\n```js\nwindow.__nightmare = {};\n__nightmare.ipc = require('electron').ipcRenderer;\n```\n\nTo benefit of all of nightmare's feedback from the browser, you can instead copy the contents of nightmare's [preload script](lib/preload.js).\n\n## Usage\n#### Installation\nNightmare 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:\n\n```bash\n$ npm install --save nightmare\n```\n\n#### Execution\nNightmare 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:\n```js\nvar Nightmare = require('nightmare'),\n  nightmare = Nightmare();\n\nnightmare.goto('http://cnn.com')\n  .evaluate(function(){\n    return document.title;\n  })\n  .end()\n  .then(function(title){\n    console.log(title);\n  })\n```\nIf you save this as `cnn.js`, you can run it on the command line like this:\n\n```bash\nnpm install nightmare\nnode cnn.js\n```\n\n#### Debugging\nThere are three good ways to get more information about what's happening inside the headless browser:\n\n1. Use the `DEBUG=*` flag described below.\n2. Pass `{ show: true }` to the [nightmare constructor](#nightmareoptions) to have it create a visible, rendered window that you can watch what's happening.\n3. Listen for [specific events](#onevent-callback).\n\nTo 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`).\n\nThis will print out some additional information about what's going on:\n\n```bash\n  nightmare queueing action \"goto\" +0ms\n  nightmare queueing action \"evaluate\" +4ms\n  Breaking News, U.S., World, Weather, Entertainment & Video News - CNN.com\n```\n\n##### Debug Flags\n\nAll nightmare messages\n\n`DEBUG=nightmare*`\n\nOnly actions\n\n`DEBUG=nightmare:actions*`\n\nOnly logs\n\n`DEBUG=nightmare:log*`\n\n#### Tests\nAutomated 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`.\n\nWhen the tests are done, you'll see something like this:\n\n```bash\nmake test\n  ․․․․․․․․․․․․․․․․․․\n  18 passing (1m)\n```\n\nNote 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`.\n\n## License (MIT)\n\n```\nWWWWWW||WWWWWW\n W W W||W W W\n      ||\n    ( OO )__________\n     /  |           \\\n    /o o|    MIT     \\\n    \\___/||_||__||_|| *\n         || ||  || ||\n        _||_|| _||_||\n       (__|__|(__|__|\n```\n\nCopyright (c) 2015 Segment.io, Inc. <friends@segment.com>\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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.\n","maintainers":[{"name":"dfrankland","email":"dylan@frankland.io"}],"time":{"modified":"2022-06-12T17:03:03.376Z","created":"2016-10-30T02:05:11.304Z","2.8.1":"2016-10-30T02:05:11.304Z"},"homepage":"https://github.com/segmentio/nightmare#readme","keywords":["nightmare","electron"],"repository":{"type":"git","url":"git+https://github.com/segmentio/nightmare.git"},"author":{"name":"Segment"},"bugs":{"url":"https://github.com/segmentio/nightmare/issues"},"license":"MIT","readmeFilename":"Readme.md"}