JavaScript makes it easy to overwrite properties and functions of the global object. I'd like to find a way to check if the original version of a global property has been replaced.
Consider someone putting this in their HTML:
<script type="text/javascript">
window.encodeURIComponent = eval;
</script>
<script type="text/javascript" src="myscript.js"></script>
If myscript.js calls the encodeURIComponent function somewhere, it will now behave unpredictably. So is there a way I can check inside myscript.js if someone has overwritten that function before I use it?
This is browser specific and definitely will not work for non-functions, but:
Calling a function's
toString
method should produce something like:Observe that the function's name matches the property's name, and its body is replaced by "
[native code]
". The idea is to remove all whitespace from this string and compare it to the expected result,"functionxxx(){[nativecode]}"
.I have no idea if it works for all browsers/functions, that's trial and error: