需要挂钩到 javascript 函数调用,有什么方法可以做到这一点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10273309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:15:59  来源:igfitidea点击:

Need to hook into a javascript function call, any way to do this?

javascript

提问by Ringo Blancke

I'm trying to hook into a function that loads Facebook's news feed:

我正在尝试连接一个加载 Facebook 新闻提要的函数:

UIIntentionalStream.instance && UIIntentionalStream.instance.loadOlderPosts();

on Facebook.com.

在 Facebook.com 上。

Is there a way for me to do this with my own JavaScript? Basically, I need to have some sort of callback - when that function is called, I'd like my own function to be called.

有没有办法用我自己的 JavaScript 来做到这一点?基本上,我需要某种回调 - 当调用该函数时,我希望调用我自己的函数。

采纳答案by Niet the Dark Absol

Try something like this:

尝试这样的事情:

var old = UIIntentionalStream.instance.loadOlderPosts;
UIIntentionalStream.instance.loadOlderPosts = function() {
    // hook before call
    old();
    // hook after call
};

Just hook in wherever you want, before or after the original function's call.

只需在原始函数调用之前或之后的任何您想要的地方挂钩。

回答by yossi eilaty

A more complete method will be:

更完整的方法是:

var old = UIIntentionalStream.instance.loadOlderPosts;
UIIntentionalStream.instance.loadOlderPosts = function(arguments) {
    // hook before call
    var ret = old.apply(this, arguments);
    // hook after call
    return ret;
};

This makes sure that if loadOlderPostsis expecting any parameters or using this, it will get the correct version of them as well as if the caller expects any return value it will get it

这确保如果loadOlderPosts需要任何参数或使用它,它将获得它们的正确版本,以及如果调用者期望任何返回值,它将获得它

回答by Eric Seastrand

Expanding on the previous posts: I have created a function that you can call to perform this "hooking" action.

扩展之前的帖子:我创建了一个函数,您可以调用它来执行此“挂钩”操作。

hookFunction(UIIntentionalStream.instance, 'loadOlderPosts', function(){
    /* This anonymous function gets called after UIIntentionalStream.instance.loadOlderPosts() has finished */
    doMyCustomStuff();
});



// Define this function so you can reuse it later and keep your overrides "cleaner"
function hookFunction(object, functionName, callback) {
    (function(originalFunction) {
        object[functionName] = function () {
            var returnValue = originalFunction.apply(this, arguments);

            callback.apply(this, [returnValue, originalFunction, arguments]);

            return returnValue;
        };
    }(object[functionName]));
}

Bonus: You should also wrap this all a closure, for good measure.

奖励:您还应该将所有这些都包裹起来,以备不时之需。