Tweaking other people’s JavaScript functions
Javascript is an interesting language and like any language, the more you use it, the more functionality you find. Without getting into the specfics, I occasionally need to modify a site’s HTML and or JavaScript with an external JavaScript file (i.e I can’t touch the page I am modifying, I can only touch one external JavaScript file). And no, this is not some nefarious activity, we are doing this with full knowledge and compliance of the sites that are loading out JavaScript file.
Anyways, you can modify a page’s javascript functions to your heart’s content. You simply cast a function to a string, remove the “function†syntax, modify the string, and then create an anonymous function and assign it to the same variable name as the existing function. Code and explanation below
function simpleFunction(param1,param2) {
alert(param2);
}
//run the function and see it alert "2";
simpleFunction('1','2');
//get the function as a string
var newFunctionString = window.simpleFunction.toString();
//remove the function construct
newFunctionString = newFunctionString.replace(/^[^{]*{/,'').replace(/}$/,'');
//replace the alert message with our own message
newFunctionString = newFunctionString.replace(/param2/,'"this is our new message"');
//create an anonymous function and assign to the function you are overwriting
window.simpleFunction = new Function('param1', 'param2',newFunctionString);
//run the modified function and see it alert "this is our new message"
simpleFunction('1','2');
We can cast the function to a string. If you were to alert the variable newFunctionString after casting it as a string, you would see the function construct (”function”, plus the name of the function and the parameters, etc…) plus the code inside the function. We want to remove this to get only the code inside the function and this can be accomplished with a regular expression. If you alerted newFunctionString after removing the function construct, you would only see “alert(param2)”‘. Using a regular expression, we can modify the code to our needs. For simplicity, I am just changing the alert message. Finally, we create an anonymous function with the parameters of the existing function and our new string that contains the modified code, and assign it to the variable “simpleFunction”, which overrides the existing function with our version!