Inject javascript into a javascript function

Grunt picture Grunt · Jan 21, 2010 · Viewed 19.2k times · Source

I've got a weird question in that I need to inject some javascript into another javascript function. I am using a framework which is locked so I can not change the existing function.

What I've got is something like this

function doSomething(){ ... }

...***

I can manipulate the ***(above) however I can not change the doSomething function... Instead I need to somehow inject a few lines of code into the end of the doSomething code.

The reason I need to do this is that the custom framework calls doSomething() and this results in an ID being returned from the server that I need to extract. This ID is only referenced inside the doSomething function so I can not catch it unless I inject code to that function (unless I've missed something).

Is there a way to do this?

Answer

August Lilleaas picture August Lilleaas · Jan 21, 2010

Alias it.

var oldDoSomething = doSomething;
doSomething = function() {
  // Do what you need to do.
  return oldDoSomething.apply(oldDoSomething, arguments);
}