Same-Origin政策并从CDN服务JS [英] Same-Origin Policy and serving JS from a CDN

查看:110
本文介绍了Same-Origin政策并从CDN服务JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从像Cloudflare这样的CDN提供我的JavaScript脚本。

I want to serve my JavaScript scripts from a CDN like cloudflare.

现在我的脚本通过ajax与我的app服务器通信。当我从CDN加载这些脚本时,同源策略限制不会发挥作用吗?

Now my scripts communicate with my app server via ajax. Wouldn't the same-origin policy restrictions come into play when I load these scripts from a CDN?

假设我的应用程序在域中:

Let's say my app is on the domain:

http://app.com

我从

http://cdn.com/xyz/all.js

现在,由于我的脚本是从与我的应用程序运行的域不同的域加载的,所以我猜相同的原始政策会阻止我与我的应用程序进行ajax通信。

Now, since my scripts are loaded from a different domain than the domain my app is running from, I guess the same origin policy would prevent me from doing ajax communication with my app.

我出错了吗?

推荐答案

不,它会奏效。这就是JSONP的工作原理。 脚本的来源是它执行的页面,而不是它来自哪里。

No, it will work. That's why JSONP works. The "origin" of the script is the page it is executed in, not where it comes from.

正如你所要求的那样,这里是一个参考(我找不到更好的,但Crockford是众所周知的)

As you asked for it, here's a reference (I couldn't find any better, but Crockford is well known)


令人惊讶的是,src属性不受限制同源政策。这意味着可以创建一个脚本元素,可以转到任何服务器,获取脚本并执行它。如果脚本导致JSON编码数据的传递,那么这是一个非常有用的东西。不幸的是,没有办法限制脚本或在执行之前检查脚本。它与页面中的脚本具有相同的权限。因此脚本可以访问和使用其cookie。它可以使用用户的授权访问原始服务器。它可以检查DOM和JavaScript全局对象,并发送它在世界任何地方找到的任何信息。 Script Tag Hack不安全,应该避免。

The src attribute, surprisingly, is not constrained by the Same Origin Policy. This means that a script element can be created which can go to any server, fetch a script, and execute it. If the script causes the delivery of JSON-encoded data, then this is a very useful thing. Unfortunately, there is no way to constrain the script or to inspect it before it executes. It runs with the same authority as scripts from the page. So the script can access and use its cookies. It can access the originating server using the user's authorization. It can inspect the DOM and the JavaScript global object, and send any information it finds anywhere in the world. The Script Tag Hack is not secure and should be avoided.

http ://javascript.crockford.com/script.html

不是真正的参考:如果这不起作用,没有人可以从谷歌的CDN中包含jQuery然后使用它的 $ .ajax 方法。

Not really a reference: If this wouldn't work, nobody could include jQuery from Google's CDN and then use it's $.ajax method.

这篇关于Same-Origin政策并从CDN服务JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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