<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 theiframe
object. Most other browsers uses thecontentDocument
property and that is the reason why we proof this property first in this OR condition. If it is not set trycontentWindow.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/