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?
The only thing I know is a straightforward approach with analysis of string representation of the function. Normally, the code
window.encodeURIComponent.toString()
should produce something like this:
function encodeURIComponent() { [native code] }
which can be easily parsed for key info function encodeURIComponent
.
If the function was overwritten by eval
, as in your example, you'll get:
function eval() { [native code] }
In general, for checking window
properties, you can create a fake iframe and compare window.[property].toString()
with iframe.contentWindow.[property].toString()
. If the comparison gives false
, the property has been changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With