2

I have iframe with id="iView" and designMode = on.

My code:

 var iframeWindow = document.getElementById('iView').contentWindow.document;                                                                                            
 var range = iframeWindow.getSelection().getRangeAt(0);

The Error I get:

Microsoft JScript runtime error: Object doesn't support this property or method

I also tried answers from
how to get selected text from iframe with javascript?

Community
  • 1
  • 1
samuel
  • 321
  • 2
  • 13

1 Answers1

2

There is no getSelection method for the document object in IE, you have to use the selection object instead.

var selText;
var iframeWindow = document.getElementById('iView').contentWindow;
if (iframeWindow.getSelection)
    selText = iframeWindow.getSelection()+"";
else if (iframeWindow.document.selection)
    selText = iframeWindow.document.selection.createRange().text;
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • why there is need to check iframeWindow.getSelection or iframeWindow.document.selection? – samuel Dec 09 '09 at 22:43
  • You're checking the functionality exists, which is essentially a browser check. If the browser doesn't support the method, those statements would return false and the script wouldn't execute - if the checks weren't there and the browser doesn't support the method an error is thrown. Alternatively, you could use a try/catch statement but this is usually the defacto method of functionality testing. – Andy E Dec 09 '09 at 22:54
  • 1
    @samuel: This is a perfectly good answer but pretty much identical to a couple found in the other question you mentioned (http://stackoverflow.com/questions/1471759/how-to-get-selected-text-from-iframe-with-javascript), so how has this given you new information? – Tim Down Dec 10 '09 at 10:40
  • lol just checked and it's most identical to your own answer in that question. Sorry if it seems like I duplicated it (I didn't) :-) +1 for it anyway. – Andy E Dec 10 '09 at 11:16
  • @Andy E: I wasn't making a particular case for my answer and I didn't think you'd duplicated it because the style's slightly different, but thanks for the upvote :) – Tim Down Dec 10 '09 at 14:11