How to get selected text from iframe using javascript?

how to get selected text from iframe using javascript?

+3
source share
2 answers
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 while iframe srcaiming at your own domain. Tested only on FireFox 3.6.7.

+2
source
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 jAndy noted, this will only work if the iframe document is served from the same domain as the containing document.

0
source

Source: https://habr.com/ru/post/1756325/


All Articles