1

Lets say this function...

function foo(param){
// original works
}

is already in-place in an html document.

I have a bookmarklet that injects an external script to the document. From that script, I want to modify the behavior of foo() function into this...

function foo(param){
// original works
bar(param);
}

bar() is a new function in the injected script. I have no problem duplicating foo in the injected script.

How do I do this?

1 Answer 1

2

Everything in javascript can be an object, including functions. With this in mind, you can create a duplicate of the old function, then override the new one while referencing the duplicate:

function foo(param){
// original works
}

var old_foo = foo;

function foo(param) {
 old_foo(param);
 bar(param);
}
Sign up to request clarification or add additional context in comments.

4 Comments

I don't know why, I was testing something similar to this and oops exception: RangeError: Maximum call stack size exceeded when I ran the new foo. PS: +1.
@JCOC611 Was it a ... <puts on sunglasses> ...StackOverflow? YEEEEEaaaaaah!
would it be more correct to store the return value of old_foo() and return that from the new foo()?, like this: function foo(param){var ret = old_foo(param);bar(param);return ret;}
@david You are correct, although I will keep my answer simple as not to confuse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.