Insert HTML code in iframe directly by Javascript

Asked

Viewed 386 times

1

Hello

I need to use a variable that contains my HTML code to display within a iframe, but my page does not display. What may be wrong ?

My code:

<html>
<head><title></title></head>
<script type="text/javascript">

function prepareFrame() {

    var bodycode =
        "<html><head><title>" +
        "Teste</title></head>" +
        "<body>teste</body></html>"                 // ESSE E O HTML
    
    var ifrm = document.createElement("iframe");
    ifrm.setAttribute("src", bodycode);             // AQUI TENTO INSERIR NO IFRAME
    ifrm.style.width = "500px";
    ifrm.style.height = "500px";
    document.body.appendChild(ifrm);
}
</script>
<body>
<script type="text/javascript">prepareFrame();</script>
</body>
</html>

Thank you

1 answer

1


You are doing this:

 ifrm.setAttribute("src", bodycode);

It turns out that src is the address of iframe, and not his html.


If you want to specify a string as source, you have to modify the srcdoc:

 ifrm.setAttribute("srcdoc", bodycode);

See working:

<html>
<head><title></title></head>
<script type="text/javascript">

function prepareFrame() {

    var bodycode =
        "<html><head><title>" +
        "Teste</title></head>" +
        "<body>teste</body></html>"
    
    var ifrm = document.createElement("iframe");
    ifrm.setAttribute("srcdoc", bodycode);
    ifrm.style.width = "500px";
    ifrm.style.height = "500px";
    document.body.appendChild(ifrm);
}
</script>
<body>
<script type="text/javascript">prepareFrame();</script>
</body>
</html>

  • 1

    Thanks for the help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.