使用 JavaScript 读取 IFrame 内容 [英] Read IFrame content using JavaScript

查看:22
本文介绍了使用 JavaScript 读取 IFrame 内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是我第一次认真对待 IFrames,我似乎无法理解一些事情:

首先是我正在测试的示例代码:

<script type="text/javascript">函数初始化(){console.log("IFrame 内容:" + window.frames['i1'].document.getElementsByTagName('body')[0].innerHTML);}<body onload="init();"><iframe name="i1" src="foo.txt"/>

文件foo.txt"如下所示:

示例文本文件

问题:

1) iframe 似乎表现为 HTML 文档,而文件文本实际上是正文的一部分.为什么 ?IFrame 是 HTML 文档的规则.iframe 的内容不能只是纯文本吗??

2) 由于某种原因,文件内容被包裹在 pre 标签中.为什么会这样?总是这样吗?

3) 我在 javascript 中的访问方法正在运行,但还有其他替代方法吗?[请使用原生 js 解决方案] 如果内容始终包含在 pre 标记中,那么我实际上必须在 pre 中查找 标记而不是查找 innerHTML

解决方案

innerHTML 确实返回元素的精确内容,它的一种返回 HTML 的非标准化方法,它等价到实际内容,在 HTML 中,等价于纯文本是

foo...</pre>.

innerText 财产..

Ok, This is my first time dealing seriously with IFrames and I cant seem to understand a few things:

First the sample code I am testing with:

<head>
<script type="text/javascript">
function init(){
  console.log("IFrame content: " + window.frames['i1'].document.getElementsByTagName('body')[0].innerHTML);
}
</script>
</head>
<body onload="init();">
<iframe name="i1" src="foo.txt"/>
</body>

the file "foo.txt" looks like this:

sample text file

Questions:

1) The iframe seems to be behaving as a HTML document and the file text is actually part of the body instead. Why ? Is it a rule for an IFrame to be a HTML document. Is it not possible for the content of an iframe to be just plain text ??

2) The file content gets wrapped inside a pre tag for some reason. Why is this so ? Is it always the case?

3) My access method in the javascript is working but is there any other alternative? [native js solutions please] If the content is wrapped in a pre tag always then I will actually have to lookup inside the pre tag rather than lookup the innerHTML

解决方案

innerHTML does not return the exact content of an element, its a non-standardized method that returns HTML which is equivalent to the real content, and in HTML the equivalent to plain text is <pre>foo...</pre>.

You might have better luck with the innerText property..

这篇关于使用 JavaScript 读取 IFrame 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆