How to restore native browser object without creating iframe?

一曲冷凌霜 提交于 2019-12-24 14:48:34

问题


I make an embedded JS code which works on thousands of different sites. I definitely want to use some standard browser features (like window.JSON.stringify), but sometimes it simply doesn't work, because a site has some code that ran before mine and replaced native object with something incompatible with my expectations (and standards of course).

Unfortunately the way of restoring native functions by deleting them (delete JSON.stringify) doesn't work in this case because I need to restore a whole object, not only its method. I've heard about a handy way to restore native object, which is iframe creation for getting a new window instance:

function getNativeJSON() {
  if (!window.JSON || !/native code/.test(window.JSON.stringify.toString()) {
      var iframe = document.createElement('iframe');
      document.documentElement.appendChild(iframe);
      return iframe.contentWindow.JSON;
  }

  return window.JSON;
}

This approach works fine for me, but sometimes (very rarely, about 1 of 10000 executions) fails. I guess this can be a consequence of some weird behavior like iframe that isn't loaded yet or anything else. Thus this method is neither elegant enough (or I just don't like it), nor can be easily reproduced and debugged.

Maybe do you know any way to restore native browser objects, like JSON?

UPDATE: Of course the iframe I use is appended to DOM before.

来源:https://stackoverflow.com/questions/37209246/how-to-restore-native-browser-object-without-creating-iframe

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