Checking if a JavaScript native function is monkey patched (2022)
3 days ago
- #JavaScript
- #Native Functions
- #Monkey Patching
- JavaScript native functions can be overridden using monkey patching, a technique to modify built-in APIs.
- Monkey patching is powerful but risky, as it can conflict with other patches or break with engine updates.
- Checking if a function is native can be done using `toString()` to look for '[native code]', but this can be tricked.
- Methods to trick `toString()` checks include adding '[native code]' in comments or overriding `toString()` itself.
- Using `bind()` or Proxies can also make monkey-patched functions appear native.
- An alternative is to compare function references stored before any potential monkey patching occurs.
- Creating a same-origin iframe to access 'clean' native functions is another method, though with limitations.
- Referential equality checks are more reliable but require storing original function references early in the script execution.
- There's no foolproof method to detect monkey patching due to JavaScript's dynamic nature.