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

tlrobinson picture tlrobinson · Apr 5, 2010 · Viewed 8.9k times · Source

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;
}

Answer

Zach picture Zach · Apr 16, 2010

I would do something like:

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