faqts : Computers : Programming : Languages : JavaScript : Frames

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 3 people (100%) answered Yes
Recently 3 of 3 people (100%) answered Yes

Entry

How can I detect if the document in an iframe is from a different domain?

Apr 16th, 2003 21:59
asFaqts sFaqts, Jean-Bernard Valentaten,


That can be done very easily, simply access the iframe through it's id 
and check its document.location.href for an unwanted domain:
var isAlien;
function hasAlienDomain(myIframeObject)
{
  var loc = myIframeObject.document.location.href;
  if (loc.indexOf('http://www.myDomain.com') != 0)
    return true;
  else
    return false;
}
isAlien = hasAlienDomain(document.getElementById('myIframe'));
HTH,
Jean
Hi Jean, 
The above won't work because if the document in the iframe is not in my 
domain, then an 'Access denied' alert is given and I wanted to find out 
how to figure out how I would know in advance if I was going to get 
that alert. I have found out the answer to my problem - i can put the 
whole thing in a try/catch block:
function hasAlienDomain(myIframeObject)
{
 try
 {
  var loc = myIframeObject.document.location.href;
 }
 catch(err)
 {
   // do something else
 }
}