set iframe.src as html

by Laurens Maneschijn

HTML

<iframe id="if"  src="data:text/html;charset=utf-8,hello there"></iframe><br>
set iframe source html via iframe.src attribute:<br>
<input type="button" onclick="klik();" value="set iframe html...">

JavaScript

function setiframehtml(iframe, html, charset){
  if(!charset){
    // if charset is not set correctly you might not see anything if there are any unknown characters in html
    charset='utf-8';
  }
  iframe.src='data:text/html;charset='+charset+','+encodeURIComponent(html);
}

function getiframehtml(iframe){
  //		return iframe.contentWindow.document.body.innerHTML;	// only html inside body
  return iframe.contentWindow.document.getElementsByTagName('html')[0].outerHTML; // all html (without doctype)
  // fails on gettings html from iframe set via above method, see note below.
}

function klik(){
  var iframe = document.getElementById('if');
  var demohtml = '<!DOCTYPE html><html><body>hello <b>there ë €</b><div style=\'float:right;\'>right</div></body></html>';
  //	var html = getiframehtml(iframe);	// fails, see note below
  var html = demohtml;
  html = prompt('zet wat html in iframe2:', html);
  setiframehtml(iframe, html);
}
window.klik = klik;

/*
note with getiframehtml() :
alas, reading original html not allowed on iframes which have their content set by html.src="data:..."
with errormessage:
thisfile.html:11 Uncaught SecurityError: Blocked a frame with origin "https://develop.user.dev" from accessing a frame with origin "null".  The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "data". Protocols must match.
*/