javascript catch function call

Viewed 27

Can I catch (trigger event) when a certain function in a big, uneditable library is called?

// big js library
var biglibrary = {
    runme: function(arguments){
        // do something...
    },
    otherfunctions: function(.....
}

Now how can I outside above catch / notice when runme is called? Can I? I tried something like this ->

$(biglibrary).on('runme', function(){
    // function was called !!!
});
1 Answers

In the vast majority of cases, you can wrap the function:

const original = biglibrary.runme;
biglibrary.runme = function(...args) {
    console.log("Function was called!");
    return original.apply(this, args);
};

const biglibrary = {
    runme: function(a, b) {
        console.log(`Original function: ${a} + ${b}`);
        return a + b;
    },
};

const original = biglibrary.runme;
biglibrary.runme = function(...args) {
    console.log("Function was called!");
    return original.apply(this, args);
}

console.log(biglibrary.runme(1, 2));

This is sometimes called "monkey-patching."

In some cases, the library may have made the runme property read-only, in which case you might be able to wrap it via Object.defineProperty:

const original = biglibrary.runme;
const descr = Object.getOwnPropertyDescriptor(biglibrary, "runme");
descr.value = function(...args) {
    console.log("Function was called!");
    return original.apply(this, args);
}
Object.defineProperty(biglibrary, "runme", descr);

const biglibrary = {
    runme: function(a, b) {
        console.log(`Original function: ${a} + ${b}`);
        return a + b;
    },
};

const original = biglibrary.runme;
const descr = Object.getOwnPropertyDescriptor(biglibrary, "runme");
descr.value = function(...args) {
    console.log("Function was called!");
    return original.apply(this, args);
}
Object.defineProperty(biglibrary, "runme", descr);

console.log(biglibrary.runme(1, 2));

If the library has made the property both read-only and non-configurable, you can't wrap it, but that's rare.

Related