SexyMF
SexyMF

Reputation: 11185

Unsafe JavaScript attempt to initiate a navigation change for frame with URL - How to try catch it

I have this script inside my iframe:

var redirectTo = "http://www.stackoverflow.com";
try {
      parent.location.href = redirectTo;
}catch(e){
      window.open(redirectTo);
    }

The browser wont catch the error in the subject.
I want the browser to do the catch block if the try block was failed.
But, even though the error happens inside the try block, the browser still see the error.

Update In a normal situation, my code working fine.
It does not working when its iframe inside iframe, in these cases I am getting the security error.
Do you have any idea Y? How can I know if my iframe is inside other Iframe?

Thanks

Upvotes: 0

Views: 6172

Answers (1)

neu-rah
neu-rah

Reputation: 1693

You can't catch that kind of errors within javascript because its not a javascript error, its a browser security feature. But you can prevent it by checking domain and port match between the url and current location. also you can't access the parent frame if its not the same domain/port of your iframe. So if parent frame domain/port is not the same as child iframe its possible that you cant even get the location unless you already know it from other source. You trying to do something you really shouldn't

(update) checking parent node

var ploc=null
try {
  if (parent && parent.nodeName=="IFRAME")
    ploc=parent.location;//assuming current node is an iframe
}catch(e){
  //it may be an iframe but from another domain
}

if (ploc) ... //ok its an iframe and is from same domain the we can proceed

Upvotes: 1

Related Questions