使用jQuery从Iframe检索html


Retrieving html from Iframe using jQuery

我已经搜索了其他问题,并尝试了建议,但答案似乎没有达到我的要求。

我正在从数据库表中检索电子邮件,并在iframe中显示电子邮件的正文。然后,我需要在一个javascript文件中获取电子邮件正文的html。

我尝试过的代码:

var body = $('#email-body').contents().find('html').html();
RETURNS: <head></head><body></body>
var body = '<?php echo $email->body;?>';
RETURNS: Invalid or unexpected token
(most likely due to the linebreaks the HTML has within it.)

第一个选项似乎应该有效,但它并没有按要求提取全部内容。

--编辑--

根据评论,我尝试了以下操作:

var iframe = document.getElementById('email-body');
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var body;
if (iframeDocument) {
    body = iframeDocument.documentElement.outerHTML;
}
RETURNS: <html><head></head><body></body></html>

--编辑2-

Iframe按如下方式填充:

<iframe id="email-body" src="/api/emails/email/{{{ $email->id }}}/body" onload="resizeIframe(this)"></iframe>

我正在测试的电子邮件:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <h2>Testing</h2>
        <div>And again.</div>
    </body>
</html>

需要在加载iframe后运行脚本才能获得正确的数据。

var body = '';
$('iframe').on('load', function() {
    body = $('#email-body').contents().find('html').html();
});