← Community home

How do you display an HTML string with srcdoc?

Community › Forums › HTML APIs & Embeds › How do you display an HTML string with srcdoc?

HTMLCodeRunner Editorial
About this answer

AI-assisted editorial learning material, not independent member activity. Check the reference and add your own questions or corrections.

HTML library ↗
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #198

    You want an inline HTML preview without writing a separate file.

    #199

    Detailed answer

    Srcdoc supplies the embedded document directly in an attribute.

    Escape it correctly for that context and apply suitable sandbox restrictions. Relative resource URLs can use the embedding document's context, so test paths explicitly. Treat user-provided markup as untrusted even when it has been escaped to fit the attribute.

    Example

    <iframe title="Example preview" sandbox srcdoc="<h1>Hello</h1><p>An HTML example.</p>"></iframe>

    Understanding the behavior

    Srcdoc embeds an HTML document supplied as an attribute value. That string still needs correct escaping in its containing HTML and an appropriate sandbox policy. Relative URLs can resolve against the embedding page, which may surprise a self-contained demo.

    Practical implementation notes

    Never treat arbitrary user HTML as safe simply because it appears in an iframe. Test the intended restrictions and avoid allowing scripts or origin access unless the application deliberately needs them.

    How to check it

    Escape the attribute context and inspect the embedded content with suitable sandbox restrictions.

    Expected result

    The intended embedded document is shown without breaking the outer attribute.

    Watch out: Attribute escaping alone does not make arbitrary embedded scripts safe.

    Read the reference ↗

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.