Simulating Keypresses / keystrokes with Javascript using Greesemonkey in Google Docs

This specific content was written 13 years ago. Please keep this in mind as it may be outdated and not adhering to best-practices.

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 http://help.dottoro.com/ljbwbehw.php  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://http://xn--mxahaychr6a.com/
// @description   Demo
// @include       https://docs.google.com/document/*
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js

// ==/UserScript==

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

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

$(button).click(function() {

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

//CTRL + A
var pressEvent = document.createEvent (“KeyboardEvent”);    //https://developer.mozilla.org/en/DOM/event.initKeyEvent
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);
}
});

 

References:
https://developer.mozilla.org/en/DOM/event.initKeyEvent
https://developer.mozilla.org/en/DOM/document.createEvent

https://developer.mozilla.org/en/DOM/event.initKeyEvent



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