

Ask HN: Editing functions within JavaScript closure, e.g. Agar.io - TechSpectator

I&#x27;ve seen Chrome extensions which remove the site&#x27;s &lt;script&gt; tag and replace it with a modified version, which isn&#x27;t ideal because any minor JS change can break it. I&#x27;ve seen using debugger tools to place a breakpoint in the closure&#x27;s init script, in order to create a global variable to reference it, which works great but requires user intervention each load. And yes, I understand that the point of the closure is to limit &#x2F; restrict public access. Are there other alternatives to access &#x2F; modify the contents of a closure, within the context of a malicious user?
======
lollipop25

      function createQueue(){
        var queue = [];
        return {
          enqueue: function(item){
            queue.push(item);
          },
          dequeue: function(){
            return queue.unshift();
          }
        };
      }
    
      var queue = createQueue();
    
    

Now you might think `queue` is inaccessible because it's in a closure, right?
Wrong. Because I can do this:

    
    
      var queue = createQueue();
      var originalPush = Array.prototype.push;
    
      Array.prototype.push = function(){
    
        // turn all enqueued to foo
        arguments[0] = 'foo';
        originalPush.apply(this, arguments);
    
        // Also know that "this" in here is the queue
      }
    

You can easily monkeypatch things in JS. There are more creative and invasive
ways to do this. You do have to know how the code runs in order to execute the
right patches.

