【问题标题】:how to obtain entire text content of a web page within a iframe using javascript如何使用 javascript 在 iframe 中获取网页的整个文本内容
【发布时间】:2011-09-25 10:42:48
【问题描述】:

我想在 iframe 中获取网页中包含的文本。

根据关于 SO 的现有问题,下面给出了在 iframe 中获取网页内容的 javascript 代码--

var myIFrame = document.getElementById(iFrameName); // Creating an object of the iframe
var content = myIFrame.contentWindow.document.body.innerHTML; // Getting it's content into a variable

问题是我只想在 iframe 中获取网页的文本内容-我不想通过获取整个内容然后解析它以删除图像/链接等来做到这一点......上面的代码在网页的正文内容中包含 HTML 标记---有没有办法只获取 iframe 中网页的文本内容?

【问题讨论】:

标签: javascript iframe


【解决方案1】:
var myIFrame = document.getElementById(iFrameName); // Creating an object of the iframe
var myIFrameBody = myIFrame.contentWindow.document.body; // Getting it's body content into a variable    

function getStrings(n, s) {
   var txt, childNodes, child, max, m, i;

   if (n.nodeType === 3) {
      txt = trim(n.data);

      if (txt.length > 0) {
         s.push(txt);
      }
   } 
   else if (n.nodeType === 1) {
      for (i = 0, max = n.childNodes.length; i < max; i++) {
         child = n.childNodes[i];
         getStrings(child, s);
      }
   }
}

/**
 Extract the html text starting from a node n.
 */
function getText(n) {
   var s = [],
       result;

   getStrings(n, s);
   result = s.join(" ");

   return result;       
}

var myIFrameText = getText(myIFrameBody);

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多