Kaigai Blog living abroad in my twenties

【My Study Note】iFrames

HTML Programming

iFrames


An iframe is HTML element that allows you to place or embed content from another website into a webpage. It’s defined using the iframe HTML tag. How it works is that it embeds another browsing instance inside the page.

What this means is that it runs the embedded webpage, similar to how a webpage runs in another tab of your web browser. Therefore, it’s running the HTML, CSS, and JavaScript of the embedded webpage.

An iframe is often used to display adverts, but it can also be used to embed content from another website, such as a social media post.

iFrame Example

<iframe src="https://www.example.com" width="200" height="150"></iframe>

Security Concern

While iframe is very useful. Its security has been a concern since its inception because it’s vulnerable to malicious code and injection.

As previously mentioned, a webpage can run JavaScript code. It’s important to ensure you trust the website you’re embedding into your own.

Fortunately, there are some attributes that can be applied to limit the behavior of the iframe.

Allow Attribute

The first attribute limits which browser features the iframe can access. There are many possible values that can be set on the allow attribute.

How to disable camera and microphone access in an iframe

<iframe src="https://www.example.com" allow="camera 'none'; microphone 'none';"></iframe>

Sandbox Attribute

The sandbox attribute is similar to the allow attribute, there are many values that can be set. The sandbox attribute limits behavior within the iframe, such as preventing files from being downloaded and preventing pop-up windows.

<iframe src="https://www.example.com" sandbox=""></iframe>

For now, the important thing to note is that when the sandbox attribute is used with an empty value, all sandbox restrictions will apply to the iframe.

<iframe src="https://www.example.com" sandbox="allow-downloads"></iframe>

Individual sandbox restrictions can be removed by adding attributes. For example, if you want to allow file downloads in the iframe, you would allow the allow downloads value.

While these restrictions help to keep your users secure, there may still be security vulnerabilities in your web browser that the embedded web page can exploit. Therefore, it’s always best to be cautious when using iframes and ensure that you trust the website that you are embedding.