javascript - 如何在 Javascript 中获取 iframe 的正文内容?

标签 javascript html iframe

<iframe id="id_description_iframe" class="rte-zone" height="200" frameborder="0" title="description">
  <html>
    <head></head>
    <body class="frameBody">
      test<br/>
    </body>
  </html>
</iframe>

我想得到的是:

test<br/>

最佳答案

确切的问题是如何使用纯 JavaScript 而不是 jQuery 来完成。

但我总是使用可以在 jQuery 源代码中找到的解决方案。 这只是一行原生 JavaScript。

对我来说,这是获取 iframe 内容的最佳、易读甚至 afaik 最短方式。

首先获取您的 iframe

var iframe = document.getElementById('id_description_iframe');

// or
var iframe = document.querySelector('#id_description_iframe');

然后使用jQuery的解决方案

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

It works even in the Internet Explorer which does this trick during the contentWindow property of the iframe object. Most other browsers uses the contentDocument property and that is the reason why we proof this property first in this OR condition. If it is not set try contentWindow.document.

选择 iframe 中的元素

然后您通常可以使用 getElementById() 甚至 querySelectorAll()iframeDocument 中选择 DOM 元素:

if (!iframeDocument) {
    throw "iframe couldn't be found in DOM.";
}

var iframeContent = iframeDocument.getElementById('frameBody');

// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');

在 iframe 中调用函数

仅从 iframe 获取 window 元素来调用一些全局函数、变量或整个库(例如 jQuery):

var iframeWindow = iframe.contentWindow;

// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');

// or
iframeContent = iframeWindow.$('#frameBody');

// or even use any other global variable
iframeWindow.myVar = window.myVar;

// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);

注意

如果您观察 same-origin policy,这一切都是可能的.

关于javascript - 如何在 Javascript 中获取 iframe 的正文内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41521917/

相关文章:

javascript - AngularJS 在 javascript 而不是 html 中应用过滤器

html - 如何将带插图的框阴影添加到包含 youtube iframe 的 div?

javascript - Keyup 函数不适用于表单输入

javascript - js导入找不到wasm文件

javascript - 计算机上文件中的视频无法使用 <video> HTML5 播放

html - 如何使用 html 和 css 像这样裁剪和设计这些图像?

javascript - iframe嵌入页面

jquery - 在 div/iframe 上使用 .remove 的替代方法

javascript - 无法使用快速中间件创建 cookie

javascript - 从 Google 电子表格中获取数据?