javascript create an iframe with strict doctype

前端 未结 2 1233
再見小時候
再見小時候 2021-01-05 12:04

I\'m building a widget that can be embedded in other sites. The widget is an iframe that is created using document.write() however I don\'t know how to apply th

2条回答
  •  礼貌的吻别
    2021-01-05 12:38

    In order to write into the iframe, you'll first need to create it, attach it to the document, and then reach inside of it to get a handle on its contentDocument.

    Here is some sample code:

    // create the iframe and attach it to the document
    var iframe = document.createElement("iframe");
    iframe.setAttribute("scrolling", "no");
    iframe.setAttribute("frameborder", "0");
    document.body.appendChild(iframe);
    
    // find the iframe's document and write some content
    var idocument = iframe.contentDocument;
    idocument.open();
    idocument.write("");
    idocument.write("");
    idocument.write("");
    idocument.write("this is the iframe");
    idocument.write("");
    idocument.close();
    
    // now have a look at your creation in the console
    console.log(idocument);
    

    See it working in this jsfiddle.

提交回复
热议问题