检查是否同源策略适用 [英] Check if same origin policy applies

查看:97
本文介绍了检查是否同源策略适用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个安全的方法来检查,如果同样的原产地政策适用于在URL之前实际上是试图使用AJAX的方法?以下是我有:

Is there a "safe" way to check if the same origin policy applies to an URL before actually trying to use ajax methods? Here is what I have:

function testSameOrigin(url) {

    var loc = window.location,
        a = document.createElement('a');

    a.href = url;

    return a.hostname == loc.hostname &&
           a.port == loc.port &&
           a.protocol == loc.protocol;
}

这类作品,但它的基础上,维基百科文章一种手动​​猜测。是否有pre-检查跨域津贴更好的办法? jQuery是即可使用。

This sort of works, but it’s kind of a manual guess based on the wikipedia article. Is there a better way of pre-checking cross domain allowance? jQuery is OK to use.

推荐答案

有趣的问题!我周围中搜索,但没有找到任何其他比你贴什么的,但我没碰到过这样的当我瞎搞一些测试code。如果你只是想要一个简单的方法来未做要求测试的URL,我会做你正在做的方式。如果你不关心发出请求进行测试,你可以试试这个:

Interesting question! I searched around and couldn't find anything other than what you posted, but I did come across this when I was messing around with some test code. If you just want a simple way to test a URL without making a request, I'd do it the way you're doing it. If you don't care about making a request to test, you could try this:

请一个简单的Ajax请求的任何URL你想要的:

Make a simple ajax request to whatever URL you want:

var ajaxRequest = $.ajax({
  url: 'http://www.google.com',
  async: false
});

它返回一个 jqXHR 对象,然后你就可以查看:

which returns a jqXHR object, which you can then check:

ajaxRequest.isRejected(); // or...
ajaxRequest.isResolved();

现在,这个唯一的问题是, isRejected()将计算为为每一个情况下,页面没有加载(即404未找​​到,等),但你可以检查状态code有:

Now, the only problem with this is that isRejected() will evaluate to true for every single case where the page doesn't load (i.e. 404 Not Found, etc.), but you can check the status code with:

ajaxRequest.status;

它看起来像上面一行将返回 0 当你试图打破同源策略,但它会返回相应的错误code(同样,即404)在其他情况下。

It looks like the above line will return 0 when you attempt to break the same origin policy, but it will return the appropriate error code (again, i.e. 404) in other cases.

所以包裹起来,也许你可以尝试做一些这样的:

So to wrap up, maybe you could try doing something like:

function testSameOrigin(testUrl) {

  var ajaxRequest = $.ajax({
    url: testUrl,
    async: false
  });

  return ajaxRequest.isRejected() && ajaxRequest.status === 0;
}

以任何方式不是一个确切的答案,但我希望它可以帮助你找出你所要寻找的!

Not a definitive answer by any means, but I hope it helps you figure out what you're looking for!

这篇关于检查是否同源策略适用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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