Scripting Gmail with Bookmarklets

July 2nd, 2007 Comments Off on Scripting Gmail with Bookmarklets

I am working on some bookmarklets for Gmail. I discovered that targetting any specific element in the Gmail window is a bit tricky, due to Google’s interesting use of frames.

It turns out that Gmail swaps between using frames named “v1” and “v2” to display the main content (at least in Firefox). If I had to guess, I’d mumble something about history and the back button and maybe cacheing :P

Anyway: here is how I find the text-editing area (it’ll be either a textarea or an iframe, depending on whether the user is using rich formatting or not):

/* gmail seems to swap between frames 'v1' and 'v2'. try both */
var success = false;
for (var i=1; i< =2 && !success; i++) {
    var ta = top.main.frames["v"+i].document.getElementById("hc_compose");
    if (ta) {
        /* do something with ta, for example: */
        ta.contentDocument.execCommand(/* something something */);
        success = true;
    else {
        //  try getting the plain text area
        ta = top.main.frames["v"+i].document.getElementById("ta_compose");
        if (ta) {
            /* do something with ta here, a textarea element */
            success = true;

I’m certain this could be done more cleanly, but you get the idea. Share and enjoy!

UPDATE: This currently doesn’t work for a “reply” editing area. I will (I hope) update the snippet to cover that case, too.

UPDATE 2: Sorry, this doesn’t work consistently. I should test more before posting :P I am now finding a frame called “v3”. Perhaps Gmail increments this continuously? In any case, I am leaving this post up for research purposes.

UPDATE 3: Got it working reliably (I think). See the fixed version!

Comments are closed.

What's this?

You are currently reading Scripting Gmail with Bookmarklets at bunnyhero dev.