问题描述
某些Web服务器使用 while(1);
前缀JSON响应,例如G。 while(1); ['id',123]
。
Some webservers prepend JSON responses with a while(1);
, e. g. while(1);['id',123]
.
这是为了防止:
但是,这种误用 JSON内容作为< script>
源仅是因为网络浏览器(例如Firefox) )执行内容类型为 application / json
的脚本:
However, this 'misuse' of JSON content as a <script>
source is only possible because webbrowsers (e. g. Firefox) execute scripts with content type application/json
:
<!-- Content-type: application/json; charset=ISO-8859-1 -->
<script src="http://code.jsontest.com/?mine=1"></script>
浏览器不能简单地忽略内容类型不匹配的远程脚本吗?例如在上面的示例中,为 application / javascript
(默认),但响应的内容类型为 application / json
。为什么它仍仍以JavaScript执行?
Can't browsers simply ignore remote scripts whose content type doesn't match? E. g. in above example, the script type would be application/javascript
(by default), but the respone has content type application/json
. Why is it still executed as JavaScript?
推荐答案
浏览器倾向于非常宽容 content-type
。当JavaScript首次出现时,还没有标准化的 content-type
。
Browsers tend to be VERY forgiving of content-type
. When JavaScript first showed up, there was no standardized content-type
for it.
其结果是许多较旧的Web服务器发送具有多种内容类型的JavaScript,而浏览器几乎接受了任何内容。如果浏览器要求使用JavaScript,则假定它已取回JavaScript并执行了它。
The upshot of this is that many older web servers send out JavaScript with a variety of content types and browsers pretty much accepted anything. If a browser requested JavaScript, it assumed it got JavaScript back and executed it.
(甚至可以将JavaScript隐藏在 GIF
并执行它。一旦引用:)
(It is even possible to hide JavaScript inside of a GIF
and have it execute. Once reference: http://iamajin.blogspot.com/2014/11/when-gifs-serve-javascript.html)
由于网络基础架构的第一法则是 不要破坏Web ,没有人愿意更改脚本的安全模型,因此必须采取其他解决方法。
Since the number one rule of web infrastructure is "Don't break the Web," nobody is willing to change the security model of scripts, and thus other work-arounds must be put into place.
换句话说-某人正在将常规JSON作为JSONP提供服务,如果浏览器拒绝执行它,全世界都会认为浏览器已损坏-而不是Web服务器。
In other words -- someone out there is serving regular JSON as JSONP and if a browser refused to execute it, the world would see the browser as being broken -- not the web server.
(感谢昆汀提供参考链接,并为我建立了时间表。)
(Thank you Quentin for the reference link and establishing a timeline for me.)
这篇关于为什么浏览器执行< script>与内容类型的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!