Is it possible to trigger a key event in a DOM window using Javascript / JQuery

Is it possible to fire a key event in DOMWindow or DOMDocument in javascript? Basically, I create a browser extension to interact with the website, and they have key event shortcuts (similar to GMail) when they perform certain actions. I found other posts on how to trigger key events correctly (The ultimate way to trigger keypress events using jQuery ), but they don't seem to work when sending key events to a document / window.

So far I have tried:

var evt = document.createEvent("KeyboardEvent"); evt.initKeyboardEvent("keydown", true, true, window, false, false, false, false, 0, "o".charCodeAt(0)) window.document.dispatchEvent(evt); 

and jQuery implementation:

 $(document).trigger({ type: 'keydown', which: "0".charCodeAt(0) }); 

I also tried doing "keydown", "keypress" and "keyup" in a row, but that didn't work either.

Any help would be greatly appreciated!

Thanks in advance.

+4
source share
3 answers

I know that you can pass additional arguments when using trigger() , but I'm not sure if you can overwrite the properties of the event object. You can transfer such data, though:

 $(document).on('keydown keyup keypress', function (event, characterCode) { if (typeof(characterCode) == 'undefined') { characterCode = -1; } console.log('type = ' + event.type); console.log('characterCode = ' + characterCode); }); 

And this will be the trigger() code:

 $(document).trigger('keydown', [ "0".charCodeAt(0) ]); 

Here is a demo: http://jsfiddle.net/A7cEE/ (see log console)

The code from the stackoverflow answer you provided works fine:

Capture:

 $(document).on('keydown', function (event) { console.log('type = ' + event.type); console.log('keyCode = ' + event.keyCode); }); 

To Trigger:

 var e = jQuery.Event('keydown'); e.keyCode = "0".charCodeAt(0); $(document).trigger(e); 

Demo: http://jsfiddle.net/A7cEE/1/

Note that .on() is new in jQuery 1.7 and in this case is the same as .bind() .

+6
source

Try the following:

 var evt = document.createEvent("KeyboardEvent"); evt.initKeyEvent ("keydown", true, true, window, false, false, false, false, 0, "o".charCodeAt(0)) window.document.dispatchEvent(evt); 
Syntax

:

 event.initKeyEvent (type, bubbles, cancelable, viewArg, ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg, keyCodeArg, charCodeArg) 

Use "initKeyEvent" instead of "initKeyboardEvent".

+1
source
 //::jQuery:: //press "L" or "l" to open Bootstrap Login Modal Form $(document).keypress(function(evt){ if (evt.charCode === 108 || evt.charCode == 76) { $('#login-modal') .modal('bs.modal.shown'); } }); 

Good luck.

0
source

Source: https://habr.com/ru/post/1386590/


All Articles