如何使用javascript从iframe中获取选定的文本

如何使用javascript从iframe中获取选定的文本

本文介绍了如何使用javascript从iframe中获取选定的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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>

使用 smth 函数我可以从某个 div 中获取选定的文本,但它不适用于 iframe.任何想法如何从 iframe 中获取选定的文本?

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 ?

推荐答案

是在外层文件上.要在 iframe 中选择文档,您需要抓取内部文档:

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()

但是请注意,WebKit 不支持document.getSelection() document.selection.尝试用 window.getSelection() 替换它,它适用于 Firefox 和 WebKit,但返回一个选择对象(范围的集合/包装器),它需要字符串:

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 是可以追溯到最早版本的基本 JavaScript;它会一直在那里,你不必去嗅探它.多个空格的 URL 编码是完全没有必要的.你甚至不需要 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('');

这篇关于如何使用javascript从iframe中获取选定的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 16:58