Check if window parent is same domain

2019-02-18 11:33发布

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
}

2条回答
Melony?
2楼-- · 2019-02-18 11:49

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
}
查看更多
Evening l夕情丶
3楼-- · 2019-02-18 12:06

You could use:

try{
    parent.document;
    // accessible
}catch(e){
    // not accessible
}
查看更多
登录 后发表回答