2

Edited question

In summary:

I got 2 sites siteA.com siteB.com

Iframe belong to siteB.com But i want allow siteA.com to iframe siteB.com page too. However anything that not siteA or siteB.com will be redirect to siteA.com

using javascript, how do i check, consider to ignore with www or without www(wildcard) and also that my site could be siteA.com/pretty-url

How do i do the check and add in the security with javascript , which any random site not authorize will result in window.top.location.href being redirect to siteA.com

Thanks for all help, new here :)

  • this may help you http://stackoverflow.com/questions/326069/how-to-identify-if-a-webpage-is-being-loaded-inside-an-iframe-or-directly-into-t – bugwheels94 Jul 29 '12 at 08:39
  • possible duplicate of [Frame Buster Buster ... buster code needed](http://stackoverflow.com/questions/958997/frame-buster-buster-buster-code-needed) – Rob W Jul 29 '12 at 08:46

1 Answers1

2

Something like this?:

if (window.top != window && !window.top.location.href.split('?')[0].split('#')[0].match('mysitedomain.com'))
{
    window.top.location.href = window.location.href;
}

The first check is making sure you only run this code if your site is in a frame.
The second check is looking to see if url of the top frame (browser window) contains your domain. We need to ignore the querystring/anchor incase it looks something like this: http://notmine.com/path/file.html?subframe=mysitedomain.com

This would still match:

http: //not*mysitedomain.com*/path

In the .match(...), you could include http:// or https://.

Update to answer your edits:

var topUrl = window.top.location.href.split('?')[0].split('#')[0];

if (window.top != window && !topUrl.match('siteA.com') && !topUrl.match('siteB.com'))
{
    window.top.location.href = "siteA.com";
}
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • use [0] after split() like split('?')[0] – bugwheels94 Jul 29 '12 at 08:40
  • 1
    This will throw errors when the page is at a different origin. Instead of manually manipulating the location.href string, use `location.protocol`, `location.host` (and perhaps `location.pathname`). – Rob W Jul 29 '12 at 08:45
  • @flem [`.match`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match) is a string method which interprets the first argument as a regular expression. A dot has a special meaning in a RegExp, it matches nearly every character. I strongly advise to incorporate the information from my previous comment. Your current "check" can easily be circumvented (assuming that the Same Origin policy does not jumps in, which is unlikely), `http://evil/?http://siteA.comhttp://siteB.com` – Rob W Jul 29 '12 at 08:52