Log in

View Full Version : Iframe redirect when directly accessed?



sp0oon
09-15-2010, 07:02 PM
Hello,

I have an iframe embed functionality on my website and I'm wondering how I can redirect users if they try to access the iframe directly.

So lets say I use the below iframe to place content from one part of my site on to another.

<iframe style="width: 530px; height: 366px;" border="0" src="http://www.mydomiain.com/images/747… scrolling="no"></iframe>

When users try to visit the url directly without the iframe ( http://www.mydomiain.com/images/74724939… ) they will get redirected to the homepage. How can I add this type of functionality to my website?

jscheuer1
09-15-2010, 08:35 PM
Javascript. But it can be a little tricky depending upon the exact circumstances and will only work when users have javascript enabled. If it's really critical though, we can make it so that users without javascript will only see a statement saying that javascript is required to view this page. They will see that regardless of whether or not the page is in the iframe. And, it has to be a page. Your post indicates it might simply be an image. If so, just use an image tag and skip the iframe.

I imagine your home page has a name like index.html or index dot something. It could have a different filename, like home dot something. There are various filenames that will load as the default page in a folder and your home page is probably one of these. That means - say it's index.htm, that it can be accessed as:


http://www.mydomiain.com/index.htm

or as just:


http://www.mydomiain.com/

So, if it's like that, on the page in the iframe, put this script in the head (substitute the actual addresses for the ones shown):


<script type="text/javascript">
if(top.location.href !== 'http://www.mydomiain.com/' && top.location.href !== 'http://www.mydomiain.com/index.htm'){
location.href = 'http://www.mydomiain.com/';
}
</script>

If you're interested in making the page virtually inaccessible for folks without javascript, let me know.

sp0oon
09-15-2010, 10:32 PM
Thanks John, that worked perfectly ;)

jscheuer1
09-16-2010, 12:36 AM
Great! Just occurred to me that the www. should be optional. So now we would have (shortening via regular expression):


<script type="text/javascript">
if(!/^http:\/\/(www\.|)mydomain\.com\/(index\.htm|)$/.test(top.location.href)){
location.href = 'http://www.mydomain.com/';
}
</script>

Hopefully you can still see where to substitute the actual values. If not, in the above, mydomain is the domain name, com is the domain extension (like com, org, biz, etc), index is the filename of the top page, htm is the file extension of the top page.