Disable external content loading inside iFrame

Viewed 404

Is there anyway of disabling loading external content inside of an iFrame? Imagine there is a an iframe defined like:

<iframe srcdoc="
    <html>
        <head>
            <title>Example Page!</title>
            <link rel='stylesheet' type='text/css' href='http://example.com/mystyle.css'>
        </head>
        <body>
            <p class='main'>Here goes the text.
            </p>

            <script src='http://example.com/js/superscript.js'>
        </body>
    </html>">
</iframe>

The loading of JS can be disabled with the allow-scripts inside of the sanbox attribute, but is there any way of disabling the load of the external css (and other external content)?

If not, is there any replacement for "rendering" html code (for example by JS), which would enable this?

2 Answers

I've made the following function to remove loading some assets from emails displayed in an iframe:

  const replaced = []
  const h = html
    .replace(/url\s*\(([\s\S]+?)\)/g, (m,url) => {
      url = url.trim()
      try {
        url = decodeURIComponent(url)
      } catch (err) {/**/}
      replaced.push(url)
      return 'url()'
    })
    .replace(/[\s'"](?:src|srcset|background)?\s*=\s*(['"])([^\1]*?)\1/g, (m,q,src) => {
      if (!src) return m // empty
      replaced.push(src)
      return ''
    })
    .replace(/<\s*link[^>]*?([\s'"]href\s*=\s*(['"])([^\2]*?)\2)/g, (m,attr,q,src) => {
      if (!src) return // empty
      replaced.push(src)
      return m.replace(attr, '')
    })

interestingly, <img alt="test"src="http://src.com/img.jpg"> is valid and will be displayed by chrome so whitespace before an attribute is actually not required, so I edited this answer to account for that...

It's probably not perfect, but you can tweak it as you see more cases by adding attributes...

Yes you can achieve it by using src not srcdoc and prefixing with data:text/html;charset=UTF-8,.

In your example:

<iframe src="data:text/html;charset=UTF-8,<html> <head> <title>Example Page!</title> <link rel='stylesheet' type='text/css' href='http://example.com/mystyle.css'> </head> <body> <p class='main'>Here goes the text. </p><script src='http://example.com/js/superscript.js'> </body> </html>">
</iframe>
Related