用于检测父框架是否具有相同原点的JavaScript? [英] JavaScript to detect if the parent frame is of the same origin?

查看:64
本文介绍了用于检测父框架是否具有相同原点的JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种跨浏览器的方式来检测父框架是否与我的框架相同,最好不要在JavaScript错误控制台上打印警告。

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.

以下似乎有效,但我想避免在控制台上打印错误(至少Safari和Chrome在访问父框架上的location.href时会这样做.Firefox抛出一个可以捕获的异常):

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


推荐答案

我会这样做:

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

这篇关于用于检测父框架是否具有相同原点的JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆