How to add HTML into an iframe

Using srcdoc to add inline HTML into an iframe

The most common use for iframes is to embed an external resource in your page, for example a social media post or video.

There are times when you will want to add your own HTML. This is where the srcdoc attribute comes into play

srcdoc allows you to specify inline HTML to embed.

The following code will create an iframe with an h1 with the text “test”;

  <iframe srcdoc="<!DOCTYPE html><h1>test</h1>">

If the browser doesn’t support srcdoc it will fall back to using the src attribute.

To do the same with JavaScript, we would do;

  const iframe = document.createElement("iframe");
  iframe.srcdoc = `<!DOCTYPE html><h1>test</h1>`;

We found this useful on a recent project where the client wanted to preview some HTML without using a third party tool.


Recent posts View all

Freelancing

Why we have ads

We run ads on the site, this article talks about how we try and make them not terrible and why we monetise in the first place

Accessibility

Writing accessible hashtags

Write accessible hashtags by camel casing them. Because ThisReadsBetter thanthisdoes.