Can key events be simulated programmatically in JavaScript?
#1 building
Non jquery versions that can be used in both webkit and gecko:
var keyboardEvent = document.createEvent("KeyboardEvent"); var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent"; keyboardEvent[initMethod]( "keydown", // event type: keydown, keyup, keypress true, // bubbles true, // cancelable window, // view: should be window false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 40, // keyCode: unsigned long - the virtual key code, else 0 0 // charCode: unsigned long - the Unicode character associated with the depressed key, else 0 ); document.dispatchEvent(keyboardEvent);
#2 building
This method supports changing the value of the key code across browsers. Resources
var $textBox = $("#myTextBox"); var press = jQuery.Event("keypress"); press.altGraphKey = false; press.altKey = false; press.bubbles = true; press.cancelBubble = false; press.cancelable = true; press.charCode = 13; press.clipboardData = undefined; press.ctrlKey = false; press.currentTarget = $textBox[0]; press.defaultPrevented = false; press.detail = 0; press.eventPhase = 2; press.keyCode = 13; press.keyIdentifier = ""; press.keyLocation = 0; press.layerX = 0; press.layerY = 0; press.metaKey = false; press.pageX = 0; press.pageY = 0; press.returnValue = true; press.shiftKey = false; press.srcElement = $textBox[0]; press.target = $textBox[0]; press.type = "keypress"; press.view = Window; press.which = 13; $textBox.trigger(press);
#3 building
You can create and schedule keyboard events that trigger the appropriate registered event handler, but, for example, if you schedule to an input element, they will not produce any text.
To fully simulate text input, you need to generate a series of keyboard events and explicitly set the text of the input element. The order of events depends on how much you want to simulate text input.
The simplest form is:
$('input').val('123'); $('input').change();
#4 building
What you can do is programmatically trigger the keyevent listener by triggering keyevents. It makes sense to allow this from a sandbox security perspective. Using this feature, you can then apply a typical Observer mode . You can call this method simulation.
Here is an example of how to do this in the W3C DOM standard and jQuery:
function triggerClick() { var event = new MouseEvent('click', { 'view': window, 'bubbles': true, 'cancelable': true }); var cb = document.querySelector('input[type=submit][name=btnK]'); var canceled = !cb.dispatchEvent(event); if (canceled) { // preventDefault was called and the event cancelled } else { // insert your event-logic here... } }
This example is adapted from: https : //developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
In jQuery:
jQuery('input[type=submit][name=btnK]') .trigger({ type: 'keypress', which: character.charCodeAt(0 /*the key to trigger*/) });
But since recently, there has been no [DOM] method to actually trigger a keyboard event leaving the browser sandbox. All major browser vendors will adhere to this security concept.
As for plug-ins such as Adobe Flash based on NPAPI, and allow to bypass sandbox: these plug-ins are Phase out ; Firefox .
detailed description:
You cannot and must not for security reasons (as Pekka has pointed out). There is always a need for user interaction between you. In addition, imagine the opportunity for browser vendors to be sued by users, as various programmatic keyboard events can lead to spoofing attacks.
See this article for alternatives and more details Article . There is always Flash based copy and paste. This is an elegant Example . At the same time, it also proves why the network is moving away from plug-in providers.
stay Choose to join the CORS policy In this case, there is a similar security mindset for programmatically accessing remote content.
The answer is:
Under normal circumstances, input keys cannot be triggered programmatically in a sandbox browser environment.
Bottom line: I'm not saying that it will be impossible in the future in special browser mode and / or game end goal privilege or similar user experience. However, before entering such a mode, users will be required to provide permissions and risks, similar to Fullscreen API model .
Useful: in the context of KeyCodes, this Tools and key mapping will come in handy.
Disclosure: answers based on here The answer.
#5 building
For those interested, you can reliably recreate keyboard input events. In order to change the text in the input area (by moving the cursor or page through the input character), you must closely follow the DOM event model: http : //www.w3.org/TR/DOM-Level-3-Events/ #h4_events-inputevents
The model should do the following:
- Focus (scheduled on DOM with target set)
Then, for each character:
- keydown (scheduled on DOM)
- Before input (scheduled on the target if the target is a text area or input)
- Key (scheduling on DOM)
- Input (scheduled on the target if the target is a text area or input)
- Change (schedule on target if selected)
- keyup (scheduled on DOM)
Then, for most cases (optional):
- Obfuscation (scheduled on DOM with target set)
In fact, this changes the text in the page through javascript (without modifying the value statement) and closes all javascript listeners / handlers appropriately. If you mess up the sequence, javascript doesn't fire in the right order, the text in the input box doesn't change, the selection doesn't change, or the cursor doesn't move to the next space in the text area.
Unfortunately, the code is written for employers based on NDA, so I can't share it, but it's possible, but you have to recreate the entire key input "stack" for each element in the right order.