How does js determine whether it is in iframe and prevent webpages from being embedded with iframe and iframe nesting?
1. How does js determine whether it is in iframe?
Js Code
// Method 1 if (self. frameElement & self. frameElement. tagName = "IFRAME") {alert ('in iframe ');} // method 2 if (window. frames. length! = Parent. frames. length) {alert ('in iframe ');} // method 3 if (self! = Top) {alert ('in iframe ');}
2. Prevent webpages from being embedded with iframe
Add the following code to the
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 will make it impossible for others to use iframe to nest any pages on your website. The effect is: Enter the address of your website, which will automatically jump to your website.
The reason is unreliable:
When someone uses the following similar code for IFRAME nested calling, the javascript code on your page may be escaped.
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:
To thoroughly prevent others from using the IFRAME framework to call their own web pages, the following method is the most reliable.
The value here is an empty page. You can also assign a value to the URL of your page.
Js Code
<script language="javascript"> if(top != self){ location.href = "about:blank"; } </script>
Another way to completely block iframe is to add:
Html code
header("X-Frame-Options: deny"); header("X-XSS-Protection: 0");
The error "Load denied by X-Frame-Options: http: // localhost/×××. php does not permit framing." is returned when loading iframe!
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!