Skip to content Skip to sidebar Skip to footer

Override Js Function From Another File

Im trying to override a JS function from Bigcartel. I have no access to the JS file. The original is: updateCart: function(cart) { $('aside .cart .count, .main header .cart').h

Solution 1:

EDIT: You are in luck. From the posted code you can see that the updateCart method is exported on the window.Store global object. The solution is to add this code after the original script loaded:

window.Store.updateCart = function(cart) {
  $('aside .cart .count, .sml .cart, .big .cart .count').htmlHighlight(cart.item_count);
  return $('aside .cart .total').htmlHighlight(Format.money(cart.total, true, true));
};

Explanation for a general situation:

All scripts loaded in a web page run in the same global scope, so overwriting a variable is as simple as inserting your script afterwards:

<script>var x = 5; // original script</script><script>
x = 2; // your inserted script</script>

From the looks of it, your function is defined as property of an object:

var x = {
   updateCart : function(cart) {
     // stuff
   }
}

So to overwrite it you need to do:

x.updateCart = function(cart) {
  // your code
}

Finally, there is one situation where you simply can't overwrite it, if function is private in the original code:

function() {
   var x = {
      updateCart: function(){}
   }
}()

// No way to access x.updateCart here

Solution 2:

Assuming you're able to find and access corresponding js object:

[theTargetObject].prototype.updateCart= function(cart) {
          $('aside .cart .count, .sml .cart, .big .cart .count').htmlHighlight(cart.item_count);
          return $('aside .cart .total').htmlHighlight(Format.money(cart.total, true, true));
}

Post a Comment for "Override Js Function From Another File"