Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a global property/function has been overwritten in JavaScript

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?

like image 204
GOTO 0 Avatar asked Apr 22 '12 07:04

GOTO 0


1 Answers

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.

like image 78
Stan Avatar answered Sep 28 '22 03:09

Stan