9

I want to disable iframe embedding pages, from my website to other websites and I make this js:

<script type="text/javascript"> if(document.referrer.indexOf("mydomain.com") != -1) { window.location = "http://www.youtube.com/watch_popup?v=oHg5SJYRHA0"; } </script>

Script works, but I have page01.php and page02.php

I want in page01.php source code insert iframe for page02.php

<iframe src="page02.php"></iframe> 

When I do this I, got redirection to:

http://www.youtube.com/watch_popup?v=oHg5SJYRHA0

How to solve this? Thanks

Aleksandar
  • 501
  • 3
  • 10
  • 21

4 Answers4

15

I would suggest you to use the X-Frame-Options header. If you are using nginx you can add this line in the server or location block:

add_header X-Frame-Options "SAMEORIGIN";

When you add this header, a modern browser will deny the request if someone tries to load your page in a frame. Note that this will not work in older browsers.

Mehmet Baker
  • 1,055
  • 9
  • 23
3

The accepted answer is good, but if you want to add additional assurances that no site can put your site into an iFrame, including other sites on the same origin, the "X-Frame-Options DENY" is recommended. Note that this should be in addition to the approved approach. See:

https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html#x-frame-options-header-types

X-Frame-Options-Header-Types

Adam Wise
  • 2,043
  • 20
  • 17
  • You say "to make sure" but that isn't supported by all browsers, so it's NOT a "sure" solution – user2342558 Dec 21 '22 at 18:37
  • @user2342558 - I added some clarification to the post that it is not a 'sure' solution, just something that should be done for better assurance than using 'SAMEORIGIN' (which is the current highest voted option). – Adam Wise Dec 21 '22 at 21:52
2

If you don't like to leave the protection to the browsers, you can still use JS.

//Check if the page is loaded in an iframe
if(window.self != window.top) {
  //Almost all browsers will deny Cross-Origin script access, so
  //we will use a try-catch block
  try {
    if(window.parent.location.hostname.indexOf("mydomain.com") == -1) {
      window.location.href = "http://www.youtube.com/watch_popup?v=oHg5SJYRHA0";
    } else {
      //You are in an iframe but Same-Origin
    }
  } catch (ex) {
    //Congrats, you are in an iframe loaded in a stranger's site!
    window.location.href = "http://www.youtube.com/watch_popup?v=oHg5SJYRHA0";
  }
}
Mehmet Baker
  • 1,055
  • 9
  • 23
1

For PHP websites you can write this line in the beginning of the script, before any output:

header( 'X-Frame-Options: DENY' );

More about header function here.

Community
  • 1
  • 1
Nuno Sarmento
  • 415
  • 5
  • 15
  • (Now I can't update this answer: you can talk about dropping this line in the beginning of a PHP script, instead of talking specifically to WordPress.) – Valerio Bozz Jun 28 '19 at 18:10