Simulating Keypresses / keystrokes with Javascript using Greesemonkey in Google Docs

This is a quick post about creating dispatching events using javascript and specifically key press events (for use with greesemonkey or whatnot and firefox).

Note that this will not work for the latest versions of firefox in many instances. I believe this is due to security updates.

Personally I am using this dispatch keypresses to google docs from a greesemonkey script.

Below the code for typing “hello world” to google docs from a greesemonkey user script.

I suspect there may be a more efficient ways though I noticed not all browsers support the same API 🙁 .
Specifically, on  we see that initKeyEvent is only available in firefox. On the other hand, initTextEventis available in IE, chrome, and Safari.

Sample Greesemonkey Script:

// ==UserScript==
// @name          Type in google docs
// @namespace     http://
// @description   Demo
// @include*
// @require

// ==/UserScript==

//find the line spacing button
var someButton = document.getElementById(“lineSpacingMenuButton”);

var button = $(“<button>Encrypt</button>”);

$(button).click(function() {

var event_object = document.getElementsByTagName(“iframe”)[0].contentDocument;

//CTRL + A
var pressEvent = document.createEvent (“KeyboardEvent”);    //
pressEvent.initKeyEvent (“keypress”, true, true, window,
true, false, false, false,
65, 0);
event_object.dispatchEvent (pressEvent);

//Must find a better way to type than char by char
var ct=”hello world”;
var i = 0;
for(;i<ct.length; i++)
var pressEvent = document.createEvent (“KeyboardEvent”);
pressEvent.initKeyEvent (“keypress”, true, true, window,
false, false, false, false,
0, ct.charCodeAt (i));
event_object.dispatchEvent (pressEvent);



Menelaos Bakopoulos

Mr. Menelaos Bakopoulos is currently pursuing his PhD both at Center for TeleInFrastruktur (CTiF) at Aalborg University (AAU) in Denmark and Athens Information Technology (AIT) in Athens, Greece. He received a Master in Information Technology and Telecommunications Systems from Athens Information Technology and a B.Sc. in Computer Science & Management Information Systems from the American College of Thessaloniki. Since April 2008 he has been a member of the Multimedia, Knowledge, and Web Technologies Group.

More Posts