Skip to main content
blog title image

3 minute read - JavaScript

Accessing Private JavaScript Variables at Runtime

Feb 12, 2019

I like to write little bots from the console to help with with application and game automation. But when the variables and objects I need are created from within anonymous functions I can’t get access. In this post I will explain how to access them.

I’ve tried writing helper code to access the methods within objects and trawl through the DOM to find specifically named objects, and that can help with a large application where the objects are all public.

But when the application is essentially one anonymous function kept alive by event handlers and timers, how do we access the objects.

The short answer is:

  • set a breakpoint on the line of code that use the object
  • in the console when the breakpoint activates, create a new reference to the object from the window

e.g. if there is a pacman object I want to access, then find a line that uses it, breakpoint the line, then from the console:

window.pacman = pacman

And I now have access to the private pacman object from the console when not in debug mode because the window now has a reference to it.

Manual Step

This requires a manual step before any of my automated bots can be used but if I write down what to ‘search for’ to find the line in the code then it is pretty easy to repeat.

Security by private objects

If we are relying on the objects being private and inaccessible due to the anonymous function then we really shouldn’t because if it is in our browser, the user can gain access to it.

Always have protection on your server side to handle anything thrown at it.

Opens Up New Options

This opens up a bunch of new options for testing and automating modern JavaScript approaches for me.

This can’t really be used for continuous integration automating or fully autonomous code injection since there is a manual step involved. But for automating tactically where the user is present, this opens up more possibilities.

Want to see it in action?

Using the simple open source Pacman clone from where all the code is wrapped and called from anonymous function. I show the steps and thought processes for gaining console access to the main game and pacman objects to allow me to write infinite life cheats.

Where to learn more?

I have some material covering this topic:

If you found this useful then you might be interested in my Online Technical Web Testing 101 course.