2

Is it possible to have a global reference only be available from a JS console, but not available to other JS running on a page?

For example, could I set a variable m to 10, so that...

<script>
    console.log(m);
</script>

Is a ReferenceError, but from the console...

console.log(m);

Prints 10?


Edit:

The responses so far only touch on the basics of scope in JavaScript, but if this is possible, it's going to be way more hacky than adding a variable to a scope that only the console can see (yes, I know this doesn't exist). Here's an almost-working example of what I'm looking for:

Object.defineProperty(
    window,
    "m",
    {
        get : function window_m_getter() {
            if (CONSOLE_OPEN) {
                return 10;
            } else {
                throw new ReferenceError('m can only be used in a console');
            }
        },
    }
);

This example would work if it were possible to detect whether the console was currently open, which it really isn't, but it's pretty close.

The answer to this question is almost certainly no, but it isn't entirely because of scope.

Community
  • 1
  • 1
mwcz
  • 8,949
  • 10
  • 42
  • 63
  • 2
    And what would be the use? – Karl-André Gagnon Apr 11 '14 at 20:08
  • 1
    No, the only way to limit the visibility of variables (or any other value) in JS is through Clousure, funciton scopes. – user3417400 Apr 11 '14 at 20:08
  • 1
    it'd not be a global variable if not everything could access it – Matt Greer Apr 11 '14 at 20:09
  • @Karl-AndréGagnon Potentially making debugging references available only from the console, but not to 'application code'. But mostly just curiosity. – mwcz Apr 11 '14 at 20:09
  • 1
    you can often make those global variables available only when debugging through clever breakpoints and use of the console during debugging. I often will do `window.foo = ...` while investigating something, then later on look at `foo` when all is done – Matt Greer Apr 11 '14 at 20:10
  • If you're trying to limit access to data in JS, you're gonna have a bad time. What kind of "debugging references" are you worried about leaking to the application? You aren't keeping sensitive data in an object on the client side, are you? – Stephen Melvin Apr 11 '14 at 20:45
  • @Steve Let's say it's an easter egg. – mwcz Apr 11 '14 at 20:47

1 Answers1

1

No.

The developer console operates in the global namespace. It's the same one every script uses, hence the name. There is no private, different namespace for the console.

The very console object you are accessing to log() is part of this namespace, and thus available to everyone.

At most, you can declare global variables for the console after you've loaded all of your scripts, at the very end of the <body>, making them unavailable until after everything runs. This, however, won't stop scripts from accessing them afterwards, from triggered events.

salezica
  • 74,081
  • 25
  • 105
  • 166