New blog address: http://hengyunabc.github.io/prevent-iframe-stealing/
When I was looking at the information, I saw this Code to prevent iframe nesting:
try { if (window.top != window.self) { var ref = document.referer; if (ref.substring(0, 2) === '//') { ref = 'http:' + ref; } else if (ref.split('://').length === 1) { ref = 'http://' + ref; } var url = ref.split('/'); var _l = {auth: ''}; var host = url[2].split('@'); if (host.length === 1) { host = host[0].split(':'); } else { _l.auth = host[0]; host = host[1].split(':'); } var parentHostName = host[0]; if (parentHostName.indexOf("test.com") == -1 && parentHostName.indexOf("test2.com") == -1) { top.location.href = "http://www.test.com"; } }} catch (e) {}
Assume that test.com and test2.com are your own domain names. When other websites maliciously nest the pages of this site, they will jump back to the homepage of this site.
There are two problems with the above code:
No matter in any language, it is not recommended to manually write code to process URLs. Because the complexity of URL is beyond ordinary people's imagination. Many security problems are caused by improper parsing of URLs. For example, when preventing CSRF, determine the referrer.
URI syntax:
http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
The best way to parse URLs in javascript is to use the browser's js engine by creating an a tag:
var getLocation = function(href) { var l = document.createElement("a"); l.href = href; return l;};var l = getLocation("http://example.com/path");console.debug(l.hostname)
The following is a concise judgment method to prevent malicious nesting of iframes:
if(window.top != window && document.referrer){ var a = document.createElement("a"); a.href = document.referrer; var host = a.hostname; var endsWith = function (str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; } if(!endsWith(host, '.test.com') || !endsWith(host, '.test2.com')){ top.location.href = "http://www.test.com"; }}
http://docs.oracle.com/javase/tutorial /networking/urls/urlInfo.html
Be careful when using functions such as contain, indexOf, and endWitch.
public static void main(String[] args) throws Exception { URL aURL = new URL("http://example.com:80/docs/books/tutorial" + "/index.html?name=networking#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("authority = " + aURL.getAuthority()); System.out.println("host = " + aURL.getHost()); System.out.println("port = " + aURL.getPort()); System.out.println("path = " + aURL.getPath()); System.out.println("query = " + aURL.getQuery()); System.out.println("filename = " + aURL.getFile()); System.out.println("ref = " + aURL.getRef()); }
http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in- javascript
http://stackoverflow.com/questions/5522097/prevent-iframe-stealing