Skip to content

Instantly share code, notes, and snippets.

@sdussaut
Last active April 21, 2016 09:57
Show Gist options
  • Save sdussaut/6dd780c8f6bb53a3e274404a83f7b3fc to your computer and use it in GitHub Desktop.
Save sdussaut/6dd780c8f6bb53a3e274404a83f7b3fc to your computer and use it in GitHub Desktop.
Add keyboard action support to NightmareJS.
var Nightmare = require( 'nightmare' );
/**
* Add keyboard events actions
*
* Usage:
* .key( keyCode ) => .key( 13 ) for the `Enter` key
* .key( optionsObject )
* optionsObject = {
* alt: [true|false],
* ctrl: [true|false],
* code: [number],
* meta: [true|false],
* shift: [true|false]
* }
*/
Nightmare.action( 'key', function ( opts, done ) {
this.evaluate_now(( opts ) => {
var options = opts;
if ( typeof options === 'number' || typeof options === 'string' ) {
options = {
code: parseInt( options ),
which: parseInt( options )
};
}
var event = document.createEvent( 'Events' );
event.initEvent( 'keydown', true, true );
event.altKey = options.alt || false;
event.ctrlKey = options.ctrl || false;
event.keyCode = options.code;
event.metaKey = options.meta || false;
event.shiftKey = options.shift || false;
event.which = options.code;
document.activeElement.dispatchEvent( event );
}, done, opts );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment