JavaScript to detect if the parent frame is of the same origin?

夙愿已清 提交于 2019-12-04 08:10:47

问题


I'm looking for a cross-browser way to detect whether the parent frame is the same origin as my frame, preferably without printing warnings on the JavaScript error console.

The following seems to work but I'd like to avoid printing errors to the console (at least Safari and Chrome do when accessing location.href on the parent frame. Firefox throws an exception which can be caught):

function parentIsSameOrigin() {
    var result = true;
    try {
        result = window.parent.location.href !== undefined;
    } catch (e) {
        result = false;
    }
    return result;
}

回答1:


I would do something like:

var sameOrigin;
try
{
    sameOrigin = window.parent.location.host == window.location.host;
}
catch (e)
{
    sameOrigin = false;
}
return sameOrigin;



回答2:


I use this method to tell if an iframe contains local content,

but you can pass it window.top from the iframe just as well

function islocal(win){
var H=location.href,
    local= H.substring(0, H.indexOf(location.pathname));
    try{
        win=win.document;
        return win && win.URL && win.URL.indexOf(local)== 0;
    }
    catch(er){
        return false
    }
}

//test case alert(islocal(window.top))




回答3:


Try this:

function parentIsSameOrigin()
{
    var result = true;
    if (window.parent)
    {
        result = Boolean
        (
            // more precise modifications needed here
            window.this.location.href.indexOf(window.parent.location.href) == 0
        );
    }
    return result;
}


来源:https://stackoverflow.com/questions/2576379/javascript-to-detect-if-the-parent-frame-is-of-the-same-origin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!