Restore overridden window. Json object

Some code that I do not control overrides the global JSON object without checking if it is already implemented:

var JSON = { org: "http://www.JSON.org", copyright: "(c)2005 JSON.org", license: "http://www.crockford.com/JSON/license.html", stringify: function(a, g) { ... 

The problem is that this version of the JSON parser is very old and has an error that causes my serialization attempts. (Others had a similar problem with this implementation.)

Can I get a built-in browser implementation? I thought delete would work , but it is not. I suspect that since JSON is an object, not a method in a prototype . Is there any other way to get to it?

+6
source share
2 answers

You can create an element of iframe (which loads the about:blank , and therefore creates a new context), and received from him a JSON object.

 function restoreJSON() { var f = document.createElement("iframe"); f.style.display = "none"; document.documentElement.appendChild(f); window.JSON = f.contentWindow.JSON; document.documentElement.removeChild(f); } 

about:blank loads synchronously, so there is no need to wait for the load event. Although this does not restore the original JSON object, it receives one black box identical to it.

+8
source

Since the code that you do not have, overrides the original, before you get to the page, you have two options:

Insert an iframe and grab the JSON from the context window (as indicated in another answer to this question during this edit) or, alternatively, just use the https://github.com/douglascrockford/JSON-js JSON library as your own insert. Please note that using Crockford provides cross-browser compliance guarantees, but native implementations are often faster.

An alternative, if you have the opportunity in the future to come to the page in front of the violating code, is to add something before this β€œcode that helps” capture the JSON object:

 <html> <head> <script> window.myJson = window.JSON; </script> .... 
+1
source

Source: https://habr.com/ru/post/918612/


All Articles