Created
March 21, 2016 13:43
-
-
Save molily/33c7801bab2a3fc5789b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* global KeyboardEvent */ | |
const supportsKeyboardEvent = (() => { | |
try { | |
new KeyboardEvent('keydown'); // eslint-disable-line no-new | |
} catch (e) { | |
return false; | |
} | |
return true; | |
})(); | |
const dispatchKeyboardEvent = (element, type, options) => { | |
let event; | |
if (supportsKeyboardEvent) { | |
console.log('new KeyboardEvent'); | |
// https://w3c.github.io/uievents/#interface-keyboardevent | |
event = new KeyboardEvent(type, options); | |
} else { | |
// https://www.w3.org/TR/uievents/#idl-interface-KeyboardEvent-initializers | |
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/initKeyboardEvent | |
event = window.document.createEvent('KeyboardEvent'); | |
const key = options.charCode || options.keyCode || options.which; | |
event.initKeyboardEvent(type, true, true, window, key, key, 0, '', false); | |
console.log('created event', event); | |
} | |
element.dispatchEvent(event); | |
}; | |
// The move event is actually bound to the window, | |
// thus it works outside of the React event system | |
export const keyPressOnWindow = (options) => { | |
dispatchKeyboardEvent(window, 'keypress', options); | |
}; | |
// The move event is actually bound to the window, | |
// thus it works outside of the React event system | |
export const keyDownOnWindow = (options) => { | |
console.log('keyDownOnWindow', options); | |
dispatchKeyboardEvent(window, 'keydown', options); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment