Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How change function call params on the fly?

I'm receiving some 'body' content from a jquery's json call, where I can get the unique javascript element returned by doing:

script_element = $(data.body)[1]

This equals to:

<script type=​"text/​javascript">​
    updater('foo', 'bar', {}, '0', constant='');
</script>​

So, typeof script_element returns "object"

And, if I run script_element.innerText, I can get:

updater('foo', 'bar', {}, '0', constant='');

After receiving this script, what I'm doing right now is just run an eval on it, but searching around I couldn't get a way to run eval changing function call params.

What I'm trying to do is change the third param of the call, in this case the {}, that can change depending on the return of the json call, so I can't just search for {}.

I could also do script_element.text.split(',')[2] for example, and change this text on the fly, but I was thinking there should be a better way to do this.

I don't know if javascript can recognize and treat a "future method call", but still think there should be a better way.

Any idea?

like image 319
Gabriel L. Oliveira Avatar asked May 23 '26 14:05

Gabriel L. Oliveira


1 Answers

What you could do is shadowing the function so as to be able to alter the third argument. You ought to define that shadowing function before fetching the JSON.

var originalUpdater = updater; // keep old function to call

// overwrite (shadowing)
updater = function(a, b, c, d, e) {
    // change c appropriately here
    originalUpdater(a, b, c, d, e);
}

Then you can still just eval it (which is not very safe, but that's not your point if I'm not mistaking), and it will call the shadow function.


A more generic shadowing method would be along the lines of:

var originalUpdater = updater; // keep old function to call

// overwrite (shadowing)
updater = function() {
    // change arguments[2] appropriately here
    originalUpdater.apply(this, arguments);
}

Fiddle: http://jsfiddle.net/n7dLX/

like image 72
pimvdb Avatar answered May 25 '26 03:05

pimvdb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!