Filling an IFRAME with dynamic content from JavaScript

前端 未结 4 568
囚心锁ツ
囚心锁ツ 2020-12-08 23:03

I have an IFRAME that should be filled with content from JavaScript. Had the content be on the server all I had to do is:

    function onIFrameFill() {
              


        
相关标签:
4条回答
  • 2020-12-08 23:16

    I think you're looking for something like:

    var iframeDoc = myIframe.contentWindow.document;
    iframeDoc.open();
    iframeDoc.write('hello world');
    iframeDoc.close();
    
    0 讨论(0)
  • 2020-12-08 23:25

    Tried setting .innerHTML but that does not work. Solution by Jeffery To works. Just want to add that myIframe.contentWindow might not work in old browsers (read IE old versions) so you can do

    var iFrameWindow = myIframe.contentWindow || myIframe.documentWindow;
    var iFrameDoc = iFrameWindow.document;
    

    then use the document open(), write() & close() as above.

    0 讨论(0)
  • 2020-12-08 23:27

    What about .innerHTML?

    myIframe.innerHTML = "This is some HTML <b>text</b>";
    
    0 讨论(0)
  • 2020-12-08 23:34

    Similar to Jeffry but using contentDocument instead.

    let iframe = document.querySelector('iframe');
    let doc = iframe.contentDocument;
    doc.open();
    doc.write('Hello world!');
    doc.close();
    
    0 讨论(0)
提交回复
热议问题