Modifying a Javascript function

in Script development
Subscribe to Modifying a Javascript function 8 posts, 6 voices

Pheran User

OK, so I confess to being a Greasemonkey newbie. This means it is entirely possible that the answer to this question is blindingly obvious - I apologize if that is the case.

I want to modify a small portion of the source code of a Javascript function on a web page. However, the function contains dynamically-generated code, so I cannot simply replace it with my own function. Also, this may not matter at all, but the function is called periodically with setInterval.

Here's an example:

function foobar() {
// various code, some dynamic
a = (b + c)/10;
// more code

Say I want to replace the formula with:

a = (b + c + d)/10;

Is this possible? Thanks!

dob Scriptwright

I don't think it's possible if you got dynamically generated content.
Maybe unsafeWindow.foobar.a would work, but I don't think so.

Mikado Scriptwright

Something like that should work:
unsafeWindow.foobar = new Function(unsafeWindow.foobar.toString().replace('function () {','').replace(/\}$/,'').replace('a = (b + c)/10; ', 'a = (b + c + d)/10;'));

You can also use uneval() or toSource() instead of toString().

Pheran User

Thanks a bunch Mikado, that works - sort of. The function replacement works, but then I ran into another problem. The Javascript block where the function is defined also contains other code that define a number of variables outside the function that are used within it. For example:

var a = 10;
function foobar() {
// various code
x = a + 20;
// more code

So once I replace foobar with the modified version, I get a bunch of "a is not defined" errors in the console, presumably since the function is no longer within its original scope. Of course the value of a is dynamically generated by the web page. I suppose I could pull that code out of the DOM and push those variables into my modified function, but is there any other way to do this?

Mikado Scriptwright

Try doing the replacement within page scope. E.g. using location hack:
location.assign("javascript: foobar = new Function(foobar.toString().replace('function () {','').replace(/\}$/,'').replace('a = (b + c)/10;', 'a = (b + c + d)/10;'));");

sizzlemctwizzle Scriptwright

Could you maybe give us the page you are doing this on? We could probably help more.

oldarney Scriptwright

sweet thanks guys. this helps me too. can some one spicify what the problem with using unsafewindow is?

znerp Scriptwright

can some one spicify what the problem with using unsafewindow is?