5

let's say that you have a script that needs to run on a page that overrides javascript's JSON.stringify, how would you ensure that your code would use the original stringify not the overridden one?

w43L
  • 565
  • 1
  • 7
  • 26
  • Run your code before the other code has a chance to modify it? I seriously doubt you can find what was there before a variable (or a function, as in this case) gets overwritten... – tucuxi Sep 21 '12 at 00:05
  • 1
    http://stackoverflow.com/questions/8580431/recovering-built-in-methods-that-have-been-overwritten Seems you can create an iframe, and access its (brand-new, unmodified) contents. Also, your question is a duplicate of this one, and should be closed as such. – tucuxi Sep 21 '12 at 00:09
  • I'm building an app that has a bookmarklet, and noticed a website overrides stringify and causes an error. since it's a bookmarklet running it before the page is not an option – w43L Sep 21 '12 at 00:11

3 Answers3

7

While I would opt for one of the other answers, here is a solution for the case when:

  1. The page cannot be altered and thus;
  2. Code cannot be run before the code that overwrites JSON.stringify and thus;
  3. Code cannot save the original function-object (to restore it or use it explicitly later).

Here is then a hack:

  1. Create an IFRAME element.
  2. Access the contentWindow property of the IFRAME element; this should then contain the original (or "a new untouched") JSON object and thus the original JSON.stringify function.

Here is the jsfiddle

3

If you are creating a library, make it a requirement that JSON.stringify should conform to the standard behavior.

There's nothing wrong with placing strict requirements on your code, and it is in fact a good idea. You just need to be certain to document the requirements.

Obviously if the original is permanently overridden, you can't use it. Placing the burden on the end user is a better solution.

If this is not for a library, but rather for a personal project, you should simply refuse to load any 3rd party code that does something as foolish as replacing a conforming method with a non-conforming one.

manager
  • 286
  • 1
  • 2
  • 1
    This is the elegant solution ("do not have this problem in the first place"). The ugly solution is here: http://stackoverflow.com/questions/8580431/recovering-built-in-methods-that-have-been-overwritten – tucuxi Sep 21 '12 at 00:11
  • Unfortunately the elegant solution is not always an option in Javascript. – w43L Sep 21 '12 at 00:19
1

Make a backup of JSON.stringify before it's overwritten. If you can't make a backup of it, use a shiv.

Ry-
  • 218,210
  • 55
  • 464
  • 476