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?
This seems to provoke an error (Too much recursion)
This works for me, even if it is ugly.
Functions are first class values in Javascript, which means that you can store them in variables (and in fact, declaring a named function is essentially assigning an anonymous function to a variable).
You should be able to do something like this:
(But, I could be wrong. My javascript's a little rusty. ;))
Injecting a few lines into the end of the
doSomething
code sounds like changing thedoSomething
function, to me. I think, unfortunately, that you’re screwed.(I’m a bit hazy on all this, but I think functions are how people who worry about such things implement information hiding in JavaScript, precisely because you can’t access their scope from outside them.)
Altering the function by working with the source code strings can be quite simple. To do it for a specific instance, try:
Now
doSomething
returns the ID. I'm not normally a fan ofeval
, but normal aspect oriented programming techniques don't apply here, due to the requirement for accessing a local variable.If
doSomething
already returns a value, try wrapping the body in atry ... finally
:To turn this into a function, we need to make the code evaluate in global scope. Originally, this answer made use of
with
to change the scope of theeval
, but this doesn't currently work in browsers. Instead,.call
is used to change the scope ofeval
towindow
.If you want to rewrite methods and anonymous functions bound to variables, change
alter
to:Note the first argument to the functions are now strings. Further improvements could be made to handle methods that aren't accessible in global scope.
Alias it.
Thanks for all your feedback. Each answer gave me a clue and as such I've come up with the following solution.