Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if window parent is same domain

My problem is that I'm creating an application that will be added to different pages in an iframe. But sometimes it will be on my own domain and sometimes on some one elses. And when it is hosted on my own domain I want to be able to call functions outside the frame.

Is it possible to check if the parent window is on the same domain (with javascript/jQuery)? At the moment I get this ugly error when trying to access somethin outside my frame when not hosted on my own site: "Error: Permission denied to access property 'document'"

Wanna do something like this:

if(window.parent is accessible) {
    // Do special stuff
} else {
   // Do nothing
}
like image 318
KungWaz Avatar asked Oct 24 '13 12:10

KungWaz


2 Answers

You could use:

try{
    parent.document;
    // accessible
}catch(e){
    // not accessible
}
like image 131
Akshaya Shanbhogue Avatar answered Nov 14 '22 11:11

Akshaya Shanbhogue


I tried checking parent document, but for some reasons in new iOS devices (chrome or safari) it didn't throw the exception, but just continued to the next step.

So I took it another step:

try{
    var doc = parent.document;
    if(!doc)
        throw new Error('Unaccessible');
    // accessible
}catch(e){
    // not accessible
}
like image 21
Ishai Jaffe Avatar answered Nov 14 '22 12:11

Ishai Jaffe