How to make an own iframe?

2019-09-20 12:31发布

问题:

How to make an iframe, where I can set the source code, not just the src? Is it possible to create one without the src?

回答1:

demo

//get the iframe
var iFrame =  document.getElementById('iframe_id');

//this is your reference variable for the iframe body tag
var iFrameBody;

//get the body
if (iFrame.contentDocument ){// FF
    iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if ( iFrame.contentWindow ){ // IE
    iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
else {
    iFrameBody = iFrame.contentDocument.body
}

iFrameBody.innerHTML = "i should be in the iframe";​

references:

  • https://stackoverflow.com/a/927023/575527
  • https://stackoverflow.com/a/4149924/575527

do note that this is bound to the "same-origin policy"



回答2:

Also, you can actually write dynamically into the document that you want, like this:

<html>
<body>
<script type="text/javascript">
    var wnd = window.open();
    wnd.document.open("text/html");
    wnd.document.write("<h1>Hello World!</h1>");
    wnd.document.close();
</script>

</body>
</html>

This code opens an output stream (in a new window; about:blank), write some text, then close the output stream.

The open() method opens an output stream to collect the output from any document.write() or document.writeln() methods.

Once all the writes are performed, the document.close() method causes any output written to the output stream to be displayed.

Notes: If a document already exists in the target, it will be cleared. If document.open() isn't called to start writing, every call to write/writeLn will render the content immediately. So for performance reasons it's good to call open and close, in order to begin and end writing. Supported by all major browsers.

References: W3C: document.open