简体   繁体   中英

how to get selected text from iframe with javascript?

如何使用javascript从iframe中选择文本?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM