恢复重写的window.JSON对象 [英] restore overridden window.JSON object

查看:101
本文介绍了恢复重写的window.JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法控制的一些代码是覆盖全局JSON对象而不检查它是否已经实现:

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) {
     ...

问题是这个版本的JSON解析器很老,而且有一个bug,这会影响我的序列化尝试。 (其他人在此实现中遇到了类似问题。)

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.)

我可以使用浏览器的本机实现吗?我认为删除可以工作,但事实并非如此。我怀疑这是因为JSON是对象而不是原型中的方法。是否有其他方法可以获得它?

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?

推荐答案

您可以创建 iframe 元素(将加载 about:blank ,从而创建一个新的上下文)并从那里获取一个JSON对象。

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 是同步加载的,因此无需等待加载事件。虽然这不是恢复原始的JSON对象,但它会得到一个与之相同的黑盒子。

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.

这篇关于恢复重写的window.JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆