How does js judge whether it is in iframe and prevent web pages from being nested by other sites with iframe

  • 2021-07-10 18:15:22
  • OfStack

1. How does js determine whether it is in iframe

Js code


// Mode 1 
if (self.frameElement && self.frameElement.tagName == "IFRAME") { 
  alert(' In iframe Medium '); 
} 
// Mode 2 
if (window.frames.length != parent.frames.length) { 
  alert(' In iframe Medium '); 
} 
// Mode 3 
if (self != top) { 
 alert(' In iframe Medium '); 
} 

2. Prevent web pages from being nested by other sites with iframe

Add the following code to your page < head > < /head > Location is sufficient:

Js code


<script language="javascript"> 
<!-- 
if (top.location != location) 
{ 
top.location.href = location.href; 
} 
//--> 
</script> 
// Or  
<script language="javascript"> 
if(self!=top){top.location.href=self.location.href;} 
</script> 

This can make others unable to use iframe nested any page of your website, the effect is: Input your website to steal the address will automatically jump to your website.

Reasons for unreliability:

When someone else makes an IFRAME nested call with a code like this, they may avoid the javascript code on your page.

Js code


<iframe src=" Your page address " name="tv" marginwidth="0" marginheight="0" scrolling="No" noResize frameborder="0" id="tv" framespacing="0" width="580" height="550" VSPACE=-145 HSPACE=-385></iframe> 
<script language="javascript"> 
var location=""; 
var navigate=""; 
frames[0].location.href=""; 
</script> 

2. The most reliable method:

In order to completely prevent others from nesting their own web pages with IFRAME framework, the following methods are the most reliable.

The value here is an empty page, or it can be assigned to the URL address of your page.

Js code


<script language="javascript"> 
if(top != self){ 
 location.href = "about:blank"; 
} 
</script> 

Another way to completely mask iframe is to add:

Html code


header("X-Frame-Options: deny"); 
header("X-XSS-Protection: 0"); 

This is also the reason why loading iframe produces the error "Load denied by X-Frame-Options: http://localhost/× × × ×. php does not permit framing."!


Related articles: