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

1 points by TechSpectator ↗ HN
I've seen Chrome extensions which remove the site's <script> tag and replace it with a modified version, which isn't ideal because any minor JS change can break it. I've seen using debugger tools to place a breakpoint in the closure'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 / restrict public access. Are there other alternatives to access / modify the contents of a closure, within the context of a malicious user?

1 comment

[ 3.3 ms ] story [ 17.0 ms ] thread

  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.