how to get selected text from iframe with javascript?

拥有回忆 提交于 2019-12-10 22:04:49

问题


how to get selected text from iframe with javascript ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3324959/how-to-get-selected-text-from-iframe-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!