Sunil Sunil - 7 months ago 13
Javascript Question

Dynamically append code to end of a function in JavaScript or jQuery

I have following JavaScript with some html. A sample demo can be found at following URL: http://js.do/sun21170/92329

My ambitious goal is to execute some code just after the

if else
part in
doSomething
function. I have no control on what is inside this function since it's in a library I use but I do want to execute some code after the last line of code is executed in this function. So, it's like I want to dynamically insert some JavaScript code at end of
doSomething
function.

Question: Is it possible to dynamically insert some code after last line of code in
doSomething
function and if yes, then how would I do it?

For example, I want to insert following line of custom code:
alert(val);
or if accessing the variables is out-of-question then insert just some other custom code like
alert("hello");
. I tried getting the body of callback function and then I guess I could append my new code, but still cannot implement my very generic requirement.

<button type="button" onclick="callback(200);">Callback gets called </button>
<script>
var callback = null;
//the function below cannot be changed
function doSomething(val) {
if (val > 150) {
alert("You are not eligible for this reward");
} else {
alert("Congrats! You have just been rewarded");
}
}


//set callback to something
callback = doSomething;

//I want to automatically execute some code when callback finishes execution without
//having to explicitly write that code within the doSomething function OR
//writing code after doSomething function is called in onclick function of button
//If this is possible, HOW WOULD I IMPLEMENT THIS?


//I can get the body of a function using below code
function getCallBackBody(callbackFunction) {
var entire = callbackFunction.toString();
var body = entire.substring(entire.indexOf("{") + 1, entire.lastIndexOf("}"));
return body;
}
</script>

Answer

You can replace doSomething with a function that calls doSomething and then calls your code. Make sure doSomething is defined first.

function doSomething(val) {
  if (val > 150) {
    alert("You are not eligible for this reward");
  } else {
    alert("Congrats! You have just been rewarded");
  }
}

var orig_doSomething = window['doSomething'];

window['doSomething'] = function () {
  orig_doSomething.apply(null, arguments);
  // your code, or a call to your function
  alert("Wow, doSomething just finished executing with these arguments - " + JSON.stringify(arguments));
};
<button type="button" onclick="doSomething(200);">Callback gets called </button>