Page 1 of 1

How to simulate a keypress using Javascript

Posted: Wed Nov 07, 2012 1:58 pm
by davidpoor
You can create a key event that will simulate a key press using Javascript. See ... 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);

I have not tested the macro, so please post any corrections....

How do you make imacros press "Enter"?

Posted: Thu Jun 27, 2013 1:44 pm
by kenanb
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();