Search code examples
javascriptgoogle-chromeconsoleuserscripts

Accessing userscript variables from the Google Chrome console


For debugging purposes, is it possible to access userscript variables from the console in Google Chrome?


Solution

  • Suppose you had a Chrome userscript with this code:

    var userscriptVar = "I'm a global variable, userscript context.";
    window.var2       = "I'm a window.scope variable, userscript context.";
    
    console.log ("Hello from the userscript.");
    


    To access these userscript variables:

    1. Determine the userscript's ID. You can see it on the extensions page (chrome://extensions/):

      Getting script's ID

    2. Switch to the script's context by clicking on the context menu at the bottom of the console:

      Switch to userscript scope

      Note that the id (pfnbaeafniclcjhfkndoploalomdmgkc) is the same as that listed on the extensions page.

    3. Now you will immediately be able to see and change the window-scoped variable (var2), but you can't see the userscript's global (userscriptVar) because the script-instance has long since finished and disappeared. :

      Accessing Script vars after script is done

    4. To access and change userscript variables, while the script is still active, set a breakpoint in the script and use the debugger. See this answer for how to do that.

      (Click for a larger image)
      Userscript paused at a breakpoint

    5. With the userscript paused at a suitable breakpoint, you can see, but not change the global values, from the console.

      (Click for a larger image)
      Can't change from console

    6. But you can change the value from the debugger:

      (Click for a larger image)
      Setting the value