w43L
w43L

Reputation: 565

How to restore an overridden function's original state in Javascript

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?

Upvotes: 5

Views: 2534

Answers (3)

user166390
user166390

Reputation:

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

Upvotes: 10

Ry-
Ry-

Reputation: 225125

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

Upvotes: 1

manager
manager

Reputation: 296

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.

Upvotes: 3

Related Questions