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

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 loadOlderPosts is 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


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.


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.

Tags:

Javascript