Skip to content

Instantly share code, notes, and snippets.

@pointofpresence
Created January 10, 2020 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pointofpresence/e956af2028028c4287f0bcb52062a116 to your computer and use it in GitHub Desktop.
Save pointofpresence/e956af2028028c4287f0bcb52062a116 to your computer and use it in GitHub Desktop.
HTML Blob in <iframe>

HTML Blob in <iframe>

A little hack to test isolated HTML template previewing within a <iframe> using Blob - without need for another server request.

A Pen by grimen on CodePen.

License.

<iframe id="blob-src-test" frameborder="0" width="300px" height="300px"></iframe>
<iframe id="document-write-test" frameborder="0" width="300px" height="300px"></iframe>
var variables = {
title: 'Hello',
image: 'https://4.bp.blogspot.com/-j49xTVdZe7g/TVnmq6phXxI/AAAAAAAABpA/Pm45FErBfQQ/s1600/hopkins%2Bduck.jpg'
};
var template = [
'<h1>',
variables.title,
'</h1>',
'<img width="80%" src="',
variables.image,
'">'
].join('');
// Alt 1: Blob approach
var blob = new Blob([template], {type: "text/html"});
var blob_url = URL.createObjectURL(blob);
var blob_iframe = document.querySelector('#blob-src-test');
blob_iframe.src = blob_url;
// Alt. 2: Document write ("old school")
var doc = document.querySelector('#document-write-test').contentWindow.document;
doc.open();
doc.write(template);
doc.close();
iframe {
margin: 10px;
}
#blob-src-test {
outline: 2px solid cyan;
}
#document-write-test {
outline: 2px solid magenta;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment