开发者

How do I modify/extend a javascript function in place by an inject script?

开发者 https://www.devze.com 2023-02-07 03:23 出处:网络
Lets say this function... function foo(param){ // original works } 开发者_开发百科 is already in-place in an html document.

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?


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消