Many sites have scripts similar to the one below. These are put to stop other people from framing the sites.
if (top.location != location) {
top.location.href = document.location.href;
}
I need some way to realize that the iframe is trying to redirect, and if it is , I will remove the iFrame and instead place a link to the site. This way, I don’t violate the usage policy of the framed website and also link to the site. I understand you can use the onbeforeunload event as discussed here and here but both seem really unethical. I remember reading somewhere about a library that does the exact same thing (digg does the same thing). Any leads?
The problem with the above solution is that it can be removed using a simple:
Once that has been called, then the
prevent_bustwill never be incremented, and that means that the website will be freely re-directed without your consent or knowledge. Bad deal.If you wanted a consistently functional version of that solution, I would recommend doing this instead:
Unfortunately, this does cause leave one problem — it is a trivial thing to retrieve the interval which has been set, unset it, and then re-direct the page:
Your best bet is actually to solve this issue server side (if you can). If you have access to the server for the website which will hold iframes, create an interim, proxy location where you pull in the website’s data and then strip the script tags:
You would then use the tag:
Unfortunately, this will mean that your iframe will be running without JavaScript which might cripple, if not completely lobotomize the website in question. You’ll also need to make sure that all of the src attributes are correctly modified for descendant nodes in the foreign site’s HTML.
On the other hand, you could have your server check the framed site and all of its JS pages to see if the RegExp top(.|[\s*(“|’))location (this will match top.location, top[“location, and top[ ‘location) exists (or if there are any references to top at all), and then use a link if it does exist and the site proper if it does not. The detriment here is that then you are forcing the user to wait for the secondary site to load twice — once on the server and once in their browser. (unless everything is done through JS, but that is generally more annoying, in my opinion).
Personally, I’m of the opinion that the “don’t frame my site” crowd can generally win most battles which involves the iframe directly. On the other hand, if code is used to process the HTML before it is appended to a web page, then the other side stands more than a fighting chance.
As a side note, all of these can be accomplished through JavaScript and AJAX, but that will generally be a bit slower. Use the server, if you can.