getSelection() returns empty in Google Mail
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.
Hey Scott,
Thanks for posting this!
It is coming in very handy.
Comment by Craig Williams — 9 September 2008 @ 7:11 am
Thanks for this info. Exactly my problem, and solution!
Gavin
Comment by Gavin — 27 September 2008 @ 10:14 pm
Any ideas how to get selected text from gmail in Chrome?
Comment by Bernard — 19 November 2008 @ 10:42 pm
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
Hi Lenny.
You can call
window.content.getSelection()in a bookmarklet, but of course that won’t work in Gmail. It looks likedocument.commandDispatcheris only available withinXUL(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
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
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
Thanks! This saved a newbie (me) a lot of time.
Comment by jason braswell — 11 August 2011 @ 4:33 pm