Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

javascript - restore overridden window.JSON object

Some code that I don't have control over is overriding the global JSON object without checking if it's 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 a bug, which is fouling up my attempts at serialization. (Others have had a similar problem with this implementation.)

Can I get at the browser's native implementation? I thought delete would work, but it doesn't. I suspect that's because JSON is an object and not a method in the prototype. Is there some other way to get at it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...