19

Facebook のニュース フィードを読み込む関数にフックしようとしています。

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

Facebook.comで。

自分の JavaScript でこれを行う方法はありますか? 基本的に、何らかのコールバックが必要です。その関数が呼び出されたときに、独自の関数を呼び出したいと思います。

4

4 に答える 4

33

より完全な方法は次のとおりです。

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が何らかのパラメーターを期待している場合、またはこれを使用している場合、呼び出し元が戻り値を期待している場合と同様に、それらの正しいバージョンが取得されます。

于 2012-05-30T11:40:38.923 に答える
14

次のようなことを試してください:

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

元の関数の呼び出しの前または後に、好きな場所にフックするだけです。

于 2012-04-23T00:10:33.753 に答える
7

以前の投稿の拡張: この「フック」アクションを実行するために呼び出すことができる関数を作成しました。

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

おまけ: 適切な手段として、これもすべてクロージャーでラップする必要があります。

于 2015-07-24T20:00:06.080 に答える
3

上記のエリックの答えに似ています。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
        }
    }
}
于 2020-06-11T21:23:53.823 に答える