/ javascript

Set content of a frame with HTML string

I ran into a problem when I was trying to display an HTML page hosted on Github. Since Github serves HTML files as raw text in the content type headers, you can't just browse to the raw file in a repo and view it. Usually RawGit works great as a shim, but I have found unpredictable behavior on larger html files, especially when they are Javascript heavy.

I wanted to embed this content on another webpage and it seemed like frames were a good match for what I wanted to accomplish. Frames usually take a URL in the src attribute to load there content. This was a problem because if I gave it the URL to the raw file, it would still honor the content type header and display it as raw text instead of HTML.

I came up with a way of creating an empty I frame and simply setting the content after it is created. You can do this using the DOM method document.writeln():

const setFrame = (el, html) => {
  if (el.contentDocument) {
    el.document = el.contentDocument;
  }
  if (el.document !== null) {
    el.document.open();
    el.document.writeln(html);
    el.document.close();
  }
};

Here's a working example: