Override JS function from another file

后端 未结 2 1109
梦毁少年i
梦毁少年i 2021-01-01 00:08

Im trying to override a JS function from Bigcartel. I have no access to the JS file.

The original is:

updateCart: function(cart) {
    $(\'aside .car         


        
相关标签:
2条回答
  • 2021-01-01 00:21

    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
    
    0 讨论(0)
  • 2021-01-01 00:45

    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));
    }
    
    0 讨论(0)
提交回复
热议问题