Capture keypress in Javascript (Google Docs)

bookmarklet, google-docs, greasemonkey, javascript

Solution

Editing in Google Docs uses an iframe. You need to attach a listener to the iframe's document. It seems to do something complicated with the iframe I haven't yet been able to work out fully, but the following seems to work for Firefox:

var iframe = document.getElementsByTagName("iframe")[0];
if (iframe) {
    iframe.contentDocument.addEventListener("keypress", function(evt) {
        console.log("iframe keypress: " + evt.which);
    }, false);
}

Problem

I'm trying to write a little greasemonkey script/bookmarklet/what have you for Google Docs. The functionality I'd like to add needs a keypress/keyup/keydown event handler (one of those three). Unfortunately, Javascript isn't my forté, and I can't seem to capture (?) a keypress event to while in the edit pane. As a last resort, I've tried the following: ``` javascript:(function(){ els = document.getElementsByTagName("*"); for(i=0;i<els.length;i++){ els[i].onkeypress=function(){alert("hello!");}; els[i].onkeyup=function(){alert("hello2!");}; els[i].onkeydown=function(){alert("hello3!");}; } })(); ``` However, this still doesn't capture keypresses in the editing pane - no annoying alerts (although it seems to work for most other sites...). I've checked in Chrome and Firefox both (I can't get it to work in either one). I tried "Log Events" in Firebug (and checked out all the registered events via a neat little extension to Firebug, Eventbug); it didn't seem like those events were firing on keypresses. Edit: To clarify [Tim], I made this screenshot with some annotations... The "editing pane" I'm talking about seems to be a bunch of Javascripted-up divs displaying what I type. Any ideas? Thanks!

Original source