Last active
April 21, 2016 09:57
-
-
Save sdussaut/6dd780c8f6bb53a3e274404a83f7b3fc to your computer and use it in GitHub Desktop.
Add keyboard action support to NightmareJS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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