Kugel
Kugel

Reputation: 19844

Accessing userscript variables from the Google Chrome console

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

Upvotes: 5

Views: 3318

Answers (3)

briankip
briankip

Reputation: 2640

What worked for me is I made the variable global. i.e

var x = "Chairman Mao";  // x not accessible to chrome
    x = "Chairman Mao";  // X becomes accessible to chrome via inspector

Upvotes: 0

Brock Adams
Brock Adams

Reputation: 93493

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

Upvotes: 3

user180100
user180100

Reputation:

hum yes. Just type the var name and hit enter to evaluate (use dir(xxx) for objects)

NB: var must be globalset on unsafeWindow

Upvotes: 1

Related Questions