简体   繁体   English

使用jQuery从iframe检索HTML

[英]Retrieving html from Iframe using jQuery

I've searched through the other questions and have tried the suggestions but the answers do not seem to be working as I require. 我搜索了其他问题并尝试了建议,但是答案似乎并没有按照我的要求工作。

I am retrieving emails from a database table and showing the body of the email within an iframe. 我正在从数据库表中检索电子邮件,并在iframe中显示电子邮件的正文。 I then need to fetch the html of the body of the email within a javascript file. 然后,我需要在javascript文件中提取电子邮件正文的html。

Code I have tried: 我尝试过的代码:

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.)

It seems like the first option should work but it isn't pulling in the full contents as requested. 似乎第一个选项应该起作用,但是它没有按要求提取全部内容。

--EDIT-- - 编辑 -

As per comments, I attempted the following: 根据评论,我尝试了以下操作:

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>

-- EDIT 2 -- -编辑2-

Iframe is populated as so: iframe的填充方式如下:

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

The email I am testing this with: 我正在测试的电子邮件:

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

Needed to run the script once the iframe had loaded to get the correct data. 加载iframe后,需要运行脚本以获取正确的数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM