如何在 iframe 的 "srcdoc" 属性中设置 HTML 代码?

How to set HTML code in "srcdoc" attribute of iframe?

<div id="email_content">
<iframe srcdoc="{$email_content}"></iframe>
</div>

如下图所示,我在 div#email_content 中使用 iframe 来显示电子邮件内容的准确预览。我正在尝试使用 srcdoc 属性在 iframe 中加载电子邮件内容。这里的电子邮件内容可能是纯文本或通过 CkEditor 设计的 HTML 内容。我尝试使用 escape、htmlentities 等。但是 srcdoc 属性中断,因为属性值包含纯 HTML 代码和引号。

任何解决方法都将被接受。

谢谢!

注意:我不想在这里使用 src 属性。

您需要在 php

中使用 htmlentities 方法
<?php
$str = '<a href="https://www.tarunlalwani.com">Go to tarunlalwani.com</a>';
echo htmlentities($str);
?>

然后将其分配给 srcdoc。它的工作原理如下 JSFiddle

https://jsfiddle.net/zpx8qw1b/1/

根据HTML5 specification for <iframe>,我们需要替换srcdoc中的quotesampersands 包含 HTML 个实体的字符串:

In the HTML syntax, authors need only remember to use """ (U+0022) characters to wrap the attribute contents and then to escape all """ (U+0022) and U+0026 AMPERSAND (&) characters, and to specify the sandbox attribute, to ensure safe embedding of content.

Notice the way that quotes have to be escaped (otherwise the srcdoc attribute would end prematurely), and the way raw ampersands (e.g. in URLs or in prose) mentioned in the sandboxed content have to be doubly escaped — once so that the ampersand is preserved when originally parsing the srcdoc attribute, and once more to prevent the ampersand from being misinterpreted when parsing the sandboxed content.

我们可以在 PHP 中使用 str_replace() 实现此目的:

$srcdoc = '<div id="foo">"Contains quoted text."</div>';
$escaped = str_replace([ '"', '&' ], [ '&quot;', '&amp;amp;' ], $srcdoc);

上面显示的替换符号 不是拼写错误。此代码产生:

<div id=&quot;foo&quot;>&quot;Contains quoted text.&quot;</div>

然后,我们可以使用转义值作为 srcdoc 属性值:

<div id="email_content">
    <iframe sandbox srcdoc="<div id=&quot;foo&quot;>&quot;Contains quoted text.&quot;</div>"></iframe>
</div>

请注意 HTML5 srcdoc 功能在 Internet Explorer 中是 not available。 Edge 从版本 79(2020 年 1 月)开始支持 srcdoc。对电子邮件客户端的支持会更低。