0

I have an iframe, created like this:

<iframe id="frame"></iframe>

Now, I also have a string in my JavaScript:

var myString = `\
<html>\
    <head>\
    </head>\
    <body>\
        <h1>Hello World!</h1>\
    </body>\
</html>\
`

I want to write the iframe code from this string. Ideally, in a perfect world, I would use something like this:

myFrame.write(myString); //Obviously this wouldn't work

How can I do this? Thanks!

Halo
  • 1,730
  • 1
  • 8
  • 31
  • Does this answer your question? [Creating an iframe with given HTML dynamically](https://stackoverflow.com/questions/10418644/creating-an-iframe-with-given-html-dynamically) – Konrad Jan 12 '23 at 16:42

1 Answers1

-1

According to W3Schools you can do the same by other method like:

<iframe srcdoc="<p>Hello world!</p>" >
  <p>Your browser does not support iframes.</p>
</iframe>

Here srcdoc attribute specifies the HTML content of the page to show in the inline frame. Source: Link1

But You want answer to do the same from javascript use the jquery and html

    <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="utf-8">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script>
         function Iframecont(){
              
                var myFrame = $("#myframe").contents().find('body');
                var htmlcontent = '<h1>Hello</h1>';
                myFrame.html(htmlcontent);
            }
        </script>
        </head>
        <body>
            <iframe id="myframe" onload="Iframecont()"></iframe>
        </body>
        </html>
  • It's 2023 https://youmightnotneedjquery.com/ – Konrad Jan 12 '23 at 17:09
  • Hi @youmightnootneedjquery What's the problem in this. This is also work. – Navin Singh Jan 12 '23 at 17:17
  • @NavinSingh, Thanks for your response! What if I need to add an external script/CDN inside the `head` tag? Would I be able to do it with `.find('head')`? – Halo Jan 12 '23 at 17:31
  • @Anye, For creating element or overwrite in head just like want to write or overwrite some meta tag so you can try in this method: `````` In the same method you can write external script/cdn using `append`. – Navin Singh Jan 12 '23 at 17:50