Dealing with iframes
Undestanding how to use iframes in a proper way
Iframes have a bad reputation in the web development world since some people claim it is vulnerable from a security perspective and others find it “dirty” to embed another document into a website. But Iframes are actually usefull in several situations, we just have to be thoughtful when implementing it. Below, I list some key aspects and characteristics of an Iframe, hoping it will somehow be useful to you (or to me in the future):
You can see more at this MDN article
-
We can declare fallback content between the
<iframe></iframe>
brackets -
It’s a good practice to insert the
src
attribute with javascript after the whole page content has loaded, in order to improve page speed and load time -
We can also use the attribute
loading="lazy"
to accomplish the same -
A big problem with Iframes is clickjacking, when the user think he’s interacting with a safe website, but in reality he’s interacting with a malicious one
-
The server can use the X-Frame-Options header to avoid the page being used as iframe in other websites, or to allow only specific websites to embed the content, avoiding clickjacking
-
Actually for new versions of browsers, it’s better to use a Content Security Policy (CSP) directive called
frame-ancestors
, where you can specify which URLs can embed your website. -
Websites implementing an iframe with third party content could specify a Content Security Policy (CSP) in the header, with a directive called
frame-src
. It will receive the sources allowed to be used as iframe sources<iframe src="...">
. This prevents XSS attacks (when attackers inject malicious scripts into a page).- The CSP mostly helps specifying server origins, source and script endpoints
-
Always use HTTPS, as they prevent embeded content accessing the parent and vice versa. This communication can be achieved with
window.postMessage()
though -
Using the
sandbox
attribute in a<iframe>
, we give only the permissions needded for it’s content, which is a good practice. If declared without any values, thesandbox
attribute impose all available restrictions. If you have to allow some functionality, start by declaring the values insidesandbox=""
quotes.- Never add allow-scripts and allow-same-origin together in the
sandbox
attribute
- Never add allow-scripts and allow-same-origin together in the
-
There is the
allow
attribute, which we can define the Feature policies for the iframe (the features enabled) -
Another attribute is the
referrerpolicy
. It indicates which referrer (source) it’s calling the target iframe resource -
We can make an iframe responsive by wrapping it in a parent container with
position: relative
and the iframe be aposition: absolute; top: 0; left: 0; width and height: 100%