Search code examples
javascriptgoogle-chromedebugginggoogle-chrome-devtoolsbreakpoints

How can I change the values of variables in a website's JavaScript code?


How can I change the values of variables in a website's JavaScript code?

I want to know because I'm building a website at the moment and, as part of the code, I have a variable whose value has important consequences for the functionality of the website. Hence my desire to know how someone can change this value (even if it only affects the website as it appears to that user).

I am particularly interested in learning how to do this in Google Chrome.


Solution

  • If you hit F12 in chrome and click on "Console" at the top, you have a fully functional JavaScript interpreter living in the scope of the website you're looking at. This means you can enter pretty much any code in the console and execute it as javascript code in the global scope of that website. Global variables in <script> tags are exposed in this scope, so if you have (for example) in your page:

    <script>
    var x = {'a': 5};
    </script>
    

    You can type in x.a = 6 in the console, press enter, and the variable will indeed be changed.

    You can even use the console to change the values of builtins, like Array.map, though this is not recommended as it can change or break the functionality of website code.