How to Simulate Key Presses or a Click with JavaScript

How to simulate keypress with a button click on Javascript?

I believe this is answered in this Stackoverflow thread: Is it possible to simulate key press events programmatically?.

To add it to the textbox you can listen to the keydown event and add the character accordingly.

How to simulate key presses in JS

You can simulate a keypress by dispatching a KeyboardEvent for keydown and keyup.

E.g. simulating keypresses for your barcode:

document.getElementById('barcode').addEventListener('click', function() {
main_input.value = theBarcode;

[...theBarcode].forEach(function(c) {
window.dispatchEvent(new KeyboardEvent('keydown',{'key':c}));
window.dispatchEvent(new KeyboardEvent('keyup',{'key':c}));
});

window.dispatchEvent(new KeyboardEvent('keydown',{'key':'Enter'}));
window.dispatchEvent(new KeyboardEvent('keyup',{'key':'Enter'}));
});

Can we simulate a key press without an event handler?

window.find(…) does that.

In general, you're out of luck though trying to orchestrate native browser functionality from within a webpage. Browser extensions can do more.

How to simulate key presses or a click with JavaScript?

Simulating a mouse click

My guess is that the webpage is listening to mousedown rather than click (which is bad for accessibility because when a user uses the keyboard, only focus and click are fired, not mousedown). So you should simulate mousedown, click, and mouseup (which, by the way, is what the iPhone, iPod Touch, and iPad do on tap events).

To simulate the mouse events, you can use this snippet for browsers that support DOM 2 Events. For a more foolproof simulation, fill in the mouse position using initMouseEvent instead.

// DOM 2 Events
var dispatchMouseEvent = function(target, var_args) {
var e = document.createEvent("MouseEvents");
// If you need clientX, clientY, etc., you can call
// initMouseEvent instead of initEvent
e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
dispatchMouseEvent(element, 'mouseover', true, true);
dispatchMouseEvent(element, 'mousedown', true, true);
dispatchMouseEvent(element, 'click', true, true);
dispatchMouseEvent(element, 'mouseup', true, true);

When you fire a simulated click event, the browser will actually fire the default action (e.g. navigate to the link's href, or submit a form).

In IE, the equivalent snippet is this (unverified since I don't have IE). I don't think you can give the event handler mouse positions.

// IE 5.5+
element.fireEvent("onmouseover");
element.fireEvent("onmousedown");
element.fireEvent("onclick"); // or element.click()
element.fireEvent("onmouseup");

Simulating keydown and keypress

You can simulate keydown and keypress events, but unfortunately in Chrome they only fire the event handlers and don't perform any of the default actions. I think this is because the DOM 3 Events working draft describes this funky order of key events:

  1. keydown (often has default action such as fire click, submit, or textInput events)
  2. keypress (if the key isn't just a modifier key like Shift or Ctrl)
  3. (keydown, keypress) with repeat=true if the user holds down the button
  4. default actions of keydown!!
  5. keyup

This means that you have to (while combing the HTML5 and DOM 3 Events drafts) simulate a large amount of what the browser would otherwise do. I hate it when I have to do that. For example, this is roughly how to simulate a key press on an input or textarea.

// DOM 3 Events
var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {
var e = document.createEvent("KeyboardEvents");
e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
var dispatchTextEvent = function(target, initTextEvent_args) {
var e = document.createEvent("TextEvent");
e.initTextEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};
var dispatchSimpleEvent = function(target, type, canBubble, cancelable) {
var e = document.createEvent("Event");
e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
target.dispatchEvent(e);
};

var canceled = !dispatchKeyboardEvent(element,
'keydown', true, true, // type, bubbles, cancelable
null, // window
'h', // key
0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick
''); // space-sparated Shift, Control, Alt, etc.
dispatchKeyboardEvent(
element, 'keypress', true, true, null, 'h', 0, '');
if (!canceled) {
if (dispatchTextEvent(element, 'textInput', true, true, null, 'h', 0)) {
element.value += 'h';
dispatchSimpleEvent(element, 'input', false, false);
// not supported in Chrome yet
// if (element.form) element.form.dispatchFormInput();
dispatchSimpleEvent(element, 'change', false, false);
// not supported in Chrome yet
// if (element.form) element.form.dispatchFormChange();
}
}
dispatchKeyboardEvent(
element, 'keyup', true, true, null, 'h', 0, '');

I don't think it is possible to simulate key events in IE.

How can I simulate a keypress in JavaScript?

As @rfsbsb pointed out from: Jquery script for simulated key press down not running keyboard shortcut

If you're trying to fire some browser or system wide keyboard shortcut
then it's a dead end - it can't be done for security reasons. If it
would be possible, you would have pages all over the Internet that
would (for example) add themself to your bookmarks without even asking
(by firing CTRL+B shortcut using Javascript).



Related Topics



Leave a reply



Submit