views:

75

answers:

2

My current solution:

function isAccessToWindowRestricted(w) {
  try {
    return !w.location.href;
  } catch (e) {
    return true;
  }
}

Any better ideas? Is there a 'legal' way without try-catch?

+2  A: 

there is no good way, as there is no way to test that a value in the parent frame even exists without throwing an Exception.

I just tried a few things, including this:

var parentURL = window.parent && window.parent.location && window.parent.location.href;

and no matter what, it'll throw an Exception due to the same origin policy. however, you can check to simply see if you're in an iframe

function checkInFrame( arg ){ arg = arg || window; return arg.parent == window; }

but to my knowledge you have to use a try { ... } catch( ... ) { ... } block (which is what it's there for).

Dan Beam
Different browsers act differently. For example Chrome doesn't throw an exception and just returns undefined for location.href of the restricted window
thorn
good to know. unfortunately, unless you're writing for just Chrome users, you'll still have to use a try / catch block, :(
Dan Beam
A: 

Looks like my solution is the answer. :)

thorn