getSelection() returns empty in Google Mail

21 February 2008

Getting selected text in a Firefox extension

I’m developing a Firefox extension for a client which does something with the currently selected text in the browser window.

The standard way to get the selection is with window.content.getSelection().

Selection is empty in Gmail

Some users reported that selected text in Gmail messages wasn’t being found by the extension. I suspect the issue is with content added using JavaScript, but I haven’t investigated.

An alternative way to getSelection

The standard Search Google for “whatever” contextual menu item does work in Gmail, so obviously it gets the selection another way.

I found a function getBrowserSelection() in the browser.js file in Firefox’s chrome. It is used by Firefox for the contextual menu search.

This is how it gets the selection:

var focusedWindow = document.commandDispatcher.focusedWindow;
var selection = focusedWindow.getSelection();

I don’t know what the difference is, but I am now using this code in my Firefox extension and it is working well.

Filed under: Uncategorized — Scott @ 12:23 pm

8 Comments »

  1. Hey Scott,

    Thanks for posting this!
    It is coming in very handy.

    Comment by Craig Williams — 9 September 2008 @ 7:11 am

  2. Thanks for this info. Exactly my problem, and solution!

    Gavin

    Comment by Gavin — 27 September 2008 @ 10:14 pm

  3. Any ideas how to get selected text from gmail in Chrome?

    Comment by Bernard — 19 November 2008 @ 10:42 pm

  4. Hi Scott, I’m not sure how to use this solution in a bookmarklet.
    Is that possible?

    Comment by Lenny — 20 March 2009 @ 12:05 am

  5. Hi Lenny.

    You can call window.content.getSelection() in a bookmarklet, but of course that won’t work in Gmail. It looks like document.commandDispatcher is only available within XUL (e.g. a Firefox extension), not for regular JavaScript in a web page or bookmarklet.

    Sorry, I don’t know of a workaround.

    Comment by Scott — 20 March 2009 @ 4:21 am

  6. Hi – I ran into the same problem in gmail with getSelection(). I think that it may be because gmail uses several frames – if you iterate over window.frames and call getSelection() on each one, you may find what you’re looking for.

    Comment by Fraser — 17 March 2010 @ 12:37 am

  7. top.document.activeElement.contentWindow.getSelection();

    For some odd reason the activeElement is always an HTML Iframe element. This works for me in Gmail.

    G’luck.

    Comment by Natch — 15 June 2010 @ 8:56 pm

  8. Thanks! This saved a newbie (me) a lot of time.

    Comment by jason braswell — 11 August 2011 @ 4:33 pm

RSS feed for comments on this post.

Leave a comment