How to simulate a keypress using Javascript

Share your tips, tricks and favorite iMacros macros, scripts and applications for web automation in general here.
Forum rules
iMacros EOL - Attention!

The renewal maintenance has officially ended for Progress iMacros effective November 20, 2023 and all versions of iMacros are now considered EOL (End-of-Life). The iMacros products will no longer be supported by Progress (aside from customer license issues), and these forums will also no longer be moderated from the Progress side.

Thank you again for your business and support.

Sincerely,
The Progress Team
Post Reply
davidpoor
Posts: 33
Joined: Fri May 23, 2008 8:45 pm
Contact:

How to simulate a keypress using Javascript

Post by davidpoor » Wed Nov 07, 2012 1:58 pm

You can create a key event that will simulate a key press using Javascript. See http://stackoverflow.com/questions/5964 ... key-events

This example presses "Enter", but can easily be modified/extended to accommodate other keys as well.

Code: Select all

  var evt = document.createEvent("KeyboardEvent");
  evt.initKeyEvent ("keypress", true, true, window,
                    0, 0, 0, 0,
                    13, 13); 
  var canceled = !body.dispatchEvent(evt);
Next, get rid of the spaces from the above, except use <SP> where a space is required, concatenate the rows, and then create a macro such as this:

Code: Select all

URL GOTO=javascript:=var<SP>evt=document.createEvent("KeyboardEvent");evt.initKeyEvent("keypress",true,true,window,0,0,0,0,13,13);body.dispatchEvent(evt);
See http://wiki.imacros.net/URL#Using_Javascript

I have not tested the macro, so please post any corrections....
kenanb
Posts: 2
Joined: Wed Sep 07, 2011 2:54 pm

How do you make imacros press "Enter"?

Post by kenanb » Thu Jun 27, 2013 1:44 pm

Even though the text input box in which I wanted iMacros to press enter was active and had the blinking text cursor, sending the event to the document body still did not work.
I had to specifically send the event to the text input element, (selected by DOM ID as "TEXTBOX" below). Also note "document.focus()" added to the end of David's example to ensure that the JS is run on the current page.

Code: Select all

URL GOTO=javascript:var<SP>evt=document.createEvent("KeyboardEvent");evt.initKeyEvent("keyup",true,true,window,0,0,0,0,13,13);document.getElementById("TEXTBOX").dispatchEvent(evt);document.focus();
Post Reply