Monday, 10 April 2023

Dynamically write contents to iframe

I use this to preview an e-mail

When I dynamically write HTML to an iframe somehow the <body> tag is omitted? The body tag holds the font-family etc. but now the whole tag is gone and the HTML document is not shown correctly

const iframe_content = $('#'+iframe_id).contents().find('html');
iframe_content.html(data.html);

contents of data.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="color-scheme" content="light dark">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>@media (prefers-color-scheme: dark){
.body_inner{background:#000 !important}
.content{border:0}
.content_inner{background:#000 !important;color:#fff !important}
}</style>
    </head>
    <body style="margin:0;padding:0;font-family:arial,helvetica,garuda">
        <div>first element</div>
    </body>
</html>

After the HTML is written to the iframe, the source of the iframe looks like this (the body tag is gone!)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="color-scheme" content="light dark">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>@media (prefers-color-scheme: dark){
.body_inner{background:#000 !important}
.content{border:0}
.content_inner{background:#000 !important;color:#fff !important}
}</style>
    </head>
    <div>first element</div>
</html>

I have tried to validate the HTML via https://validator.w3.org/ and no errors



from Dynamically write contents to iframe

No comments:

Post a Comment