diff --git a/Readme.md b/Readme.md index b2583b32..7e998b36 100644 --- a/Readme.md +++ b/Readme.md @@ -318,6 +318,12 @@ Listen for `console.log(...)`, `console.warn(...)`, and `console.error(...)`. ###### .on('console', function(type, errorMessage, errorStack)) This 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`. +#### .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](https://github.com/atom/electron/blob/master/docs/api/browser-window.md#wincapturepagerect-callback)), the image will be clipped to the rectangle. diff --git a/lib/nightmare.js b/lib/nightmare.js index 91a372e3..3d2bea09 100644 --- a/lib/nightmare.js +++ b/lib/nightmare.js @@ -348,6 +348,24 @@ Nightmare.prototype.on = function(event, handler) { return this; }; +/** + * once + */ + +Nightmare.prototype.once = function(event, handler) { + this.child.once(event, handler); + return this; +}; + +/** + * removeEventListener + */ + +Nightmare.prototype.removeListener = function(event, handler) { + this.child.removeListener(event, handler); + return this; +}; + /** * Queue */ diff --git a/test/index.js b/test/index.js index 28b6c445..fa61838b 100644 --- a/test/index.js +++ b/test/index.js @@ -1037,7 +1037,7 @@ describe('Nightmare', function () { }); }); - describe('events', function () { + describe.only('events', function () { var nightmare; beforeEach(function() { @@ -1154,6 +1154,43 @@ describe('Nightmare', function () { confirm.should.equal('my confirm'); response.should.equal('hello!'); }); + + it('should only fire once when using once', function*() { + var events = 0; + nightmare.once('page', function(type, message) { + events++; + }); + + yield nightmare + .goto(fixture('events')) + events.should.equal(1); + }); + + it('should remove event listener', function*() { + var events = 0; + var handler = function(type, message) { + if (type === 'alert') { + events++; + } + }; + + nightmare.on('page', handler); + + yield nightmare + .goto(fixture('events')) + .evaluate(function(){ + alert('alert one'); + }); + + nightmare.removeListener('page', handler); + + yield nightmare + .evaluate(function(){ + alert('alert two'); + }); + + events.should.equal(1); + }); }); describe('options', function () {