Why do browsers execute <script> with content
Some webservers prepend JSON responses with a while(1);
, eg while(1);['id',123]
.
This is to prevent JSON hijacking:
This is to ensure some other site can't do nasty tricks to try to steal your data. For example, by replacing the array constructor, then including this JSON URL via a tag, a malicious third-party site could steal the data from the JSON response. By putting a while(1); at the start, the script will hang instead. @bdonlan, https://stackoverflow.com/a/871508/1647737
However, this 'misuse' of JSON content as a <script>
source is only possible because webbrowsers (eg 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>
Browsers tend to be VERY forgiving of content-type
. When JavaScript first showed up, there was no standardized content-type
for it.
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.
(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)
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.
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.)
链接地址: http://www.djcxy.com/p/1316.html上一篇: 如何以编程方式美化JSON?
下一篇: 为什么浏览器使用内容执行<script>