【问题标题】:Need to hook into a javascript function call, any way to do this?需要挂钩到一个javascript函数调用,有什么办法吗?
【发布时间】:2012-05-03 15:18:04
【问题描述】:

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

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

在 Facebook.com 上。

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

【问题讨论】:

    标签: javascript


    【解决方案1】:

    更完整的方法是:

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

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

    【讨论】:

      【解决方案2】:

      试试这样的:

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

      只需在原始函数调用之前或之后的任何地方挂接即可。

      【讨论】:

        【解决方案3】:

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

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

        奖励:您还应该将这一切都包装在一个闭包中,这是很好的衡量标准。

        【讨论】:

          【解决方案4】:

          与上面 Eric 的回答类似。使用 ES6 时,此功能适用于异步和同步功能:

          export function createHook(obj, targetFunction, hookFunction) {
              let temp = obj[targetFunction]
              obj[targetFunction] = function (...args) {
                  let ret = temp.apply(this, args)
                  if (ret && typeof ret.then === 'function') {
                      return ret.then((value)=>{hookFunction([value, args]); return value;})
                  } else {
                      hookFunction([ret, args])
                      return ret
                  }
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2010-11-30
            • 1970-01-01
            • 1970-01-01
            • 2021-12-03
            • 1970-01-01
            • 2011-09-16
            • 1970-01-01
            相关资源
            最近更新 更多