How to simulate a keypress using Javascript

Share your tips, tricks and favorite iMacros macros, scripts and applications for web automation in general here.

Moderator: iMacros Moderators

How to simulate a keypress using Javascript

by davidpoor on Wed Nov 07, 2012 6:58 am

You can create a key event that will simulate a key press using Javascript. See

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....
Posts: 33
Joined: Fri May 23, 2008 1:45 pm

How do you make imacros press "Enter"?

by kenanb on Thu Jun 27, 2013 6:44 am

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();
Posts: 2
Joined: Wed Sep 07, 2011 7:54 am

Return to How-To's and useful iMacros: All other topics

Who is online

Users browsing this forum: No registered users and 1 guest