restore overridden window.JSON object

寵の児 提交于 2019-12-01 16:44:57

You can create an iframe element (which will load about:blank and hence create a new context) and get a JSON object from there.

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 is loaded synchronously, so no need to wait for the load event. While this isn't restoring the original JSON object, it is getting one black-box identical to it.

Since the code that you don't have control over is overriding the original before you come along in the page, you have two options:

Inject an iframe and grab the JSON off the contextWindow (as indicated in the other answer on this question at the time of this edit), or, alternately, just use the https://github.com/douglascrockford/JSON-js JSON library as your own insert. Note that using Crockford's does give cross-browser-guarantees of conformance, but the native implementations are often faster.

An alternative if you have the ability in the future to come along on the page before the offending code, is to inject something before that offending "code that helps" to grab the JSON object:

<html>
  <head>
    <script>
      window.myJson = window.JSON;
    </script>
 ....
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!