Javascript – load a document string into an iframe

ajaxhtmliframejavascriptjquery

I have a string (fetched via ajax), which is an entire html document (doctype to < /html>). Does anyone know of a way to load it into an iframe?

I cannot simply specify the url that returned the document in the src of the iframe, since the response may have come from a post, and repeating it may have ill effects. Also, I can't submit it to the iframe the first time, since I can't predict absolutely that the result will be a document and not some json. Basically, I can't recall the url, I must be able to use the version I have (a string).

jQuery is fair game, since that's what I'm using.

Best Solution

You can do this using a data URI. A data URI is a way to load inline data as if you're loading external data. They look like this: data:<mimetype>,<data>. For HTML, the mimetype is text/html, and in your case, the data is something like this: <!DOCTYPE><html><head><title>Iframe</title></head><body>Hi!</body></html>. If we put this in a data URI, we get something like the following:

data:text/html,<!DOCTYPE><html><head><title>Iframe</title></head><body>Hi!</body></html>

When we set this as the src of the iframe, it looks like this.

var string = '<!DOCTYPE><html><head><title>Iframe</title></head><body>Hi!</body></html>',
  iframe = $('#iframe')

iframe.attr('src', 'data:text/html,' + string)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="iframe" src=""></iframe>