How to set HTML content into an iframe

前端 未结 6 1739
醉酒成梦
醉酒成梦 2020-11-28 07:16

I have a HTML string


  Hello world
 

and I wan

相关标签:
6条回答
  • 2020-11-28 07:54

    You could use:

    document.getElementById('iframe1').contentWindow.document.write("<html><body>Hello world</body></html>");
    

    Here's a jsFiddle, which works in all major browsers.

    Note that instead of contentDocument.write you should use contentWindow.document.write: this makes it work in IE7 as well.

    0 讨论(0)
  • 2020-11-28 08:04

    How about document.documentElement.innerHTML. But do know that everything in the page will be replaced even the script that does that.

    For an iframe it would be like this myIFrame.contentWindow.document.documentElement.innerHTML

    0 讨论(0)
  • 2020-11-28 08:10

    I have a problem with 'origin' with the answers here. This is how it's work for me:

    const frame1 = document.createElement('iframe');
    frame1.name = 'frame1';
    //not have to set this style,just for demo
    frame1.style.position = 'absolute';
    frame1.style.height = '800px';
    frame1.style.top = '100px';
    frame1.style.left = '100px';
    frame1.style.background = 'white';
    
    document.body.appendChild(frame1);
    const frameDoc =
      frame1.contentWindow || frame1.contentDocument.document || 
      frame1.contentDocument;
    
    frameDoc.document.write('<html><head><title></title><body>Hello world</body></html>');
    frameDoc.document.close();
    
    0 讨论(0)
  • 2020-11-28 08:11

    The innerHTML is a bit tricky especially in IE, where elements like thead are read-only and cause a lot of trouble.

    Based on the documentation on msdn you might try documentMode which provides a innerHTML property.

    myIFrame = myIFrame.contentWindow ||
        myIFrame.contentDocument.document ||
        myIFrame.contentDocument;
    myIFrame.document.open();
    myIFrame.document.write('Your HTML Code');
    myIFrame.document.close();
    

    this might only work in IE.

    • http://msdn.microsoft.com/en-us/library/ie/ms535862(v=vs.85).aspx
    • http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
    • http://msdn.microsoft.com/en-us/library/ie/ms533897(v=vs.85).aspx
    0 讨论(0)
  • 2020-11-28 08:12
    var htmlString="<body>Hello world</body>";
    var myIFrame = document.getElementById('iframe1');
    myIFrame.src="javascript:'"+htmlString+"'";
    

    With html5 you'll be able to use the srcdoc attribute.

    0 讨论(0)
  • 2020-11-28 08:16

    try it:

    $('iframe').load(function() {
        $(this).contents().find('body').append("Hello world");
    }); 
    

    update:

    $(function(){
        $('iframe').load(function() {
            $(this).contents().find('body').append("Hello world");
        }); 
    })
    
    0 讨论(0)
提交回复
热议问题