how to get selected text from iframe with javascript ?
Asked
Active
Viewed 5,019 times
3
-
1Please add some more information. Is the iframe pointing to a page on your domain? – Pekka Jul 24 '10 at 11:49
-
1Possible duplicate: http://stackoverflow.com/questions/1471759/how-to-get-selected-text-from-iframe-with-javascript – Tim Down Jul 24 '10 at 20:14
2 Answers
2
var $ifx = $('<iframe src="filename.html" height=200 width=200></iframe>').appendTo(document.body);
$(document.body).bind('click', function(){
var u_sel;
if(window.getSelection){
u_sel = ifx[0].contentWindow.getSelection();
// u_sel.text() InternetExplorer !!
alert(u_sel);
}
});
That should do it, as long as the iframe src
is targeting your own domain
.
Tested only on FireFox 3.6.7
so far.

jAndy
- 231,737
- 57
- 305
- 359
-
Also, the `getSelection()` method of a window object returns a `Selection` object, not a string. You need to call `toString()` on it. – Tim Down Jul 25 '10 at 18:21
-
@Tim Down: No need to call `.toString()` since javascript already does the job for you. – jAndy Jul 25 '10 at 18:37
-
Well yes, if you happen to be alerting it. Won't work so well if, say, you wanted to do a string substitution on it and tried to call `replace()`. – Tim Down Jul 25 '10 at 18:40
0
function getIframeSelectionText(iframe) {
var win = iframe.contentWindow;
var doc = iframe.contentDocument || win.document;
if (win.getSelection) {
return win.getSelection().toString();
} else if (doc.selection && doc.selection.createRange) {
return doc.selection.createRange().text;
}
}
var iframe = document.getElementById("your_iframe");
alert(getIframeSelectionText(iframe));
As noted by jAndy, this will only work if the iframe document is served from the same domain as the containing document.

Tim Down
- 318,141
- 75
- 454
- 536