Selected Text In An IFrame

A recent post on the Sencha forums asked how to access the selected text within an inline frame (IFrame). Though the answer appears quite straightforward it is actually a little tricky to pick a route through the potential pitfalls to find an implementation that works with all major browsers.

This isn't really an ExtJS question, it's more an exercise in negotiating the idiosyncrasies of IFrames. Once you get past that it's just the standard text-selection problem.

The code below works on all the browsers that were tested. Note that browser security policies may prevent JavaScript access between pages that don't have the same origin.

        function getSelectedText(frameId) {
            // In ExtJS use:
            // var frame = Ext.getDom(frameId);
            var frame = document.getElementById(frameId);

            var frameWindow = frame && frame.contentWindow;
            var frameDocument = frameWindow && frameWindow.document;

            if (frameDocument) {
                if (frameDocument.getSelection) {
                    // Most browsers
                    return String(frameDocument.getSelection());
                }
                else if (frameDocument.selection) {
                    // Internet Explorer 8 and below
                    return frameDocument.selection.createRange().text;
                }
                else if (frameWindow.getSelection) {
                    // Safari 3
                    return String(frameWindow.getSelection());
                }
            }

            /* Fall-through. This could happen if this function is called
               on a frame that doesn't exist or that isn't ready yet. */
            return '';
        }
    

Here's a demo of the code in action.

Selected text:

Browsers tested:

  • Internet Explorer 6
  • Internet Explorer 7
  • Internet Explorer 8
  • Internet Explorer 9
  • Firefox 1.5
  • Firefox 2
  • Firefox 3
  • Firefox 3.6
  • Firefox 5
  • Safari 3
  • Safari 4
  • Safari 5
  • Chrome 13
  • Opera 11.50
-----