Monkey patching – Extend built-in Javascript functions with custom code

You might have come across scenarios where you wished that a built-in Javascript function would be doing a little more than it actually does, meaning that you would like to add your own custom code right before or after the actual function code. So you would rather want to extend than to override the function in order to keep its original functionality. Well, it can be done in Javascript and it is know by the obscure name of monkey patching. The following Javascript snippet works cross-browser and explains monkey patching by extending the built-in function appendChild:

// Call the initExtend function once, either onload or at the bottom of your page
function initExtend() {
    // Get all elements of the body
    var allElements = document.body.getElementsByTagName("*");
    // Iterate through all elements
    for (var i = 0;i < allElements.length; i++) {
        // Call extend function
        extend(allElements[i]);
    }
}
function extend(element) {
    // Save the original functionality of appendChild
    element.originalAppendChild = element.appendChild;
 
    // Redefine appendChild
    element.appendChild = function(node) {
 
        // Add your custom code here to execute it before the original functionality
 
        // Call the orignal functionality of appendChild
        this.originalAppendChild(node);
 
        // Add your custom code here to execute it after the original functionality
 
        /*
         * Call extend() recursively to enable the customized code
         * for the newly appended element
         */
        extend(node);
    };
}
Please vote: How useful was this post for you?
Current rating:
(4 out of 5)
This entry was posted in Javascript and tagged , . Bookmark the permalink.

Comments are closed.