Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

how to get selected text from iframe with javascript?

<html>
 <body>
  <script type="text/javascript">

   function smth() {

    if (document.getSelection) {
    var str = document.getSelection();
    if (window.RegExp) {
      var regstr = unescape("%20%20%20%20%20");
      var regexp = new RegExp(regstr, "g");
      str = str.replace(regexp, "");
    }
    } else if (document.selection && document.selection.createRange) {
     var range = document.selection.createRange();
     var str = range.text;
    }   

    alert(str);
   }
  </script>   

    <iframe id="my"  width="300" height="225">
   .....some html ....
    </iframe>      

    <a href="#" onclick="smth();">AA</a>
 </body>    
</html>

with smth function i can get selected text from some div, but it doesnt work with iframe. any ideas how to get selected text from iframe ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

document.getSelection

Is on the outer document. To get the selection of the document in the iframe you need to grab the inner document:

var iframe= document.getElementById('my');
var idoc= iframe.contentDocument || iframe.contentWindow.document; // ie compatibility

idoc.getSelection()

Note however that WebKit does not support document.getSelection() or document.selection. Try replacing it with window.getSelection() which works in both Firefox and WebKit, but returns a selection object (a collection/wrapper around Ranges), which needs stringing:

var idoc= iframe.contentDocument || iframe.contentWindow.document;
var iwin= iframe.contentWindow || iframe.contentDocument.defaultView;

''+iwin.getSelection()

I'm not sure what the point of this is:

if (window.RegExp) {
  var regstr = unescape("%20%20%20%20%20");
  var regexp = new RegExp(regstr, "g");
  str = str.replace(regexp, "");
}

RegExp is basic JavaScript dating back to the very earliest version; it will always be there, you don't have to sniff for it. The URL-encoding of multiple spaces is quite unnecessary. You don't even need RegExp as such, a string replace could be written as:

str= str.split('     ').join('');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...