javascript tutorial - [Solved-5 Solutions] JSON responses - javascript - java script - javascript array


Why does Google prepend while(1);to their JSON responses ?

Solution 1:

  • It prevents JSON hijacking.
  • Contrived example: say Google has a URL like which returns the first 50 messages of our inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a lt;script> tag. The URL is visited with our cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.
  • The while(1); or &&&BLAH&&& prevents this: an AJAX request at will have full access to the text content, and can strip it away. But a <script> tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.
  • This does not address the issue of cross-site request forgery.

Solution 2:

This is to ensure some other site can't do nasty tricks to try to steal our data. For example, by replacing the array constructor, then including this JSON URL via a lt;script> 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.A same-site request using XHR and a separate JSON parser, on the other hand, can easily ignore the while(1); prefix.


That would be to make it difficult for a third-party to insert the JSON response into an HTML document with the lt;script> tag. Remember that the lt;script> tag is exempt from the Same Origin Policy.

Solution 4:

It prevents it from being used as the target of a simple lt;script> tag. (Well, it doesn't prevent it, but it makes it unpleasant.) That way bad guys can't just put that script tag in their own site and rely on an active session to make it possible to fetch our content.edit — note the comment (and other answers). The issue has to do with subverted built-in facilities, specifically the Object and Array constructors. Those can be altered such that otherwise innocuous JSON, when parsed, could trigger attacker code.

Solution 5:

Since the tag is exempted from the Same Origin Policy which is a security necessity in the web world, while(1) when added to the JSON response prevents misuse it in the tag.

Related Searches to javascript tutorial - JSON responses