简体   繁体   English

外部js文件中的相同原始策略

[英]same origin policy in external js file

if in the website http://www.mysite.com there's an external js file added as 如果在网站http://www.mysite.com添加了外部js文件

<script src="http://www.yoursite.com/new.js"></script> 

within the http://www.yoursite.com/new.js js file, there's an ajax call to a script in http://www.yoursite.com/new.js 在中http://www.yoursite.com/new.js js文件,还有一个AJAX调用的脚本在http://www.yoursite.com/new.js

in such a case will there be the same-origin policy security problem, as it's calling a script in a site from another website? 在这种情况下,是否存在同源策略安全问题,因为它在另一个网站的网站中调用脚本?

There will be a problem. 会有问题。 new.js run in the scope of mysite.com , not yoursite.com . new.js运行在mysite.com的范围内,而不是yoursite.com

EDIT: a more detailed explanation would be: when mysite.com is openning a tag, that script runs in the scope of the current page. 编辑:更详细的解释是:当mysite.com打开一个标签时,该脚本在当前页面的范围内运行。 The source of the script does not matter: it can be inline, local source, or remote source, it is still considered part of mysite. 脚本的来源无关紧要:它可以是内联,本地源或远程源,它仍然被认为是mysite的一部分。

As you know, scripts in mysite.com cannot access anything on yoursite.com due to the same origin policy. 如您所知,由于原始策略相同,mysite.com中的脚本无法访问yoursite.com上的任何内容。 So you cannot do this. 所以你不能这样做。

As an advanced option for cross-origin communication look at jsonp . 作为跨源通信的高级选项,请查看jsonp It will require yoursite.com to provide a special handling, but if you have control on both sites then this should not be a problem. 它将要求yoursite.com提供特殊处理,但如果您对两个站点都有控制权,那么这应该不是问题。

JSONP is precisely what you're looking for: http://en.wikipedia.org/wiki/JSON JSONP正是您所需要的: http//en.wikipedia.org/wiki/JSON

The 5,000m overview is that JSONP uses the same mechanism for requesting external scripts as you're using above. 5,000米概述是JSONP使用相同的机制来请求外部脚本,就像您在上面使用的那样。 The difference is that your server will recognise this and will package up the JSON response as the argument to a callback method. 区别在于您的服务器将识别这一点,并将JSON响应打包为回调方法的参数。 When your site receives this 'script', it executes it thereby returning the data directly into your callback method. 当您的站点收到此“脚本”时,它会执行该脚本,从而将数据直接返回到您的回调方法中。

If you are able to use a framework like jQuery, most of the client side would be transparently handled for you. 如果您能够使用像jQuery这样的框架,那么大多数客户端都将为您透明地处理。 Check it out here: http://api.jquery.com/jQuery.getJSON/ 在这里查看: http//api.jquery.com/jQuery.getJSON/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM