Skip to content

Instantly share code, notes, and snippets.

@molily
Created March 21, 2016 13:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save molily/33c7801bab2a3fc5789b to your computer and use it in GitHub Desktop.
Save molily/33c7801bab2a3fc5789b to your computer and use it in GitHub Desktop.
/* 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