Prevent web page from being loaded inside iFrame.

This is a short tutorial on how to prevent your web pages from being loaded inside iFrames on other websites. Having your content being loaded on other websites can be annoying, especially if said websites are stealing search engine traffic from you or placing their advertisements above your content.

To do this, we can use JavaScript on the client side or PHP on the server side (or both, for that matter).

Using JavaScript.

Have a look at the following JavaScript code:

The code above checks to see if the current window is the top window. If the page in question is not the top window, then the JavaScript code above assumes that the page has been embedded in an iFrame. It then attempts to “break out” of the iFrame by switching the top property / window with the current page (in this case, the “current page” is your page).

Using PHP.

If you’re using PHP or another server-side language such as Python or Java, then you can set a “Content Security Policy” by sending a Content-Security-Policy header to the browser:

In the code above, we set the Content-Security-Policy value to frame-ancestors ‘none’ using PHP’s header function.

Thankfully, most modern browsers will accept the “Content Security Policy” header – including Chrome, Edge, Firefox, Opera and Safari.

Facebook Comments