How to deny the access of your website to third party websites in an iframe


To deny the access from a document in an iframe, we'll need to modify the X-Frame-Options of the document using a meta tag and (or) implement a framebuster using Javascript. Websites like YouTube disallow its access from iframes, if you try to embed their website from in an iframe i.e :

<iframe width="1000px" height="700px" src="https://www.youtube.com" ></iframe>

You'll find the error message in the console :

Deny access from an iframe for all

The following tag will prevent the access from a website independently from the request.

<meta http-equiv="X-Frame-Options" content="deny">

The deny value, will cause that the page cannot be displayed in a frame, regardless of the site that tries to do it (that includes yours).

Deny access from other websites

The following tag will prevent the access from a website independently from the request.

<meta http-equiv="X-Frame-Options" content="sameorigin">

The sameorigin value, will cause that the page cannot be displayed in a frame from other domains but yours. You'll still be capable of embed your own page within an iframe in your own domain.

How reliable is this method

If you really asked to yourself (without read this paragraph), then you're making a great question, indeed the X-Frame-Options are sensible to the Clickjacking attack.

Clickjacking, or click hijacking is a malicious technique of tricking Internet users to reveal confidential information or take control of your computer when they click on seemingly innocent websites. You can read more about this technique here.

You can increase the protection for the website that is not mean to be loaded in an iframe implementing a Framekiller. Framekillers are implemented using JavaScript that validates if the current window is the main window, you can use the following snippet written in JS as a simple Framekiller in the webpage you want to block in iframes.

if (top.location != self.location) {
    top.location = self.location.href;
}

This solution works, however it  still unreliable. The following situations may render the script above useless:

  • The user agent does not support JavaScript.
  • The user agent supports JavaScript but the user has turned support off.
  • The user agent's JavaScript support is flawed or partially implemented.

Finally it is recommended that you use the X-Frame-Options at pages which are not meant to run into a frame and use the script too.

Have fun !

Become a more social person