Why Google Chrome console throws "SyntaxError: Unexpected token }" when inputted (
Edit: I found the exact code that gets evaluated. The code is in "src/third_party/WebKit/Source/WebCore/inspector/InjectedScriptSource.js".
Before the Chrome console evaluates your code, it wraps it in a with
block to bring the command-line functions into scope. So what you type is actually evaluated inside braces. The unexpected "}" token is the one put in automatically by Chrome.
The code that Chrome passes to eval
is
with ((window && window.console && window.console._commandLineAPI) || {}) {
<your code here>
};
Because it's a simple text substitution, the following example works and the result is an object which you can expand to see the answer
property:
} 0, { answer: 42
Which (reformatted) is equivalent to:
with ((window && window.console && window.console._commandLineAPI) || {}) {
}
0, { answer: 42 };
The }
at the beginning closes the with
block. The 0,
part is necessary to force the object literal to be parsed as an expression instead of another block. Then, the { answer: 42
is the beginning of an object literal that gets closed by the inserted }
token.
For more fun, here are some other inputs that work (and their results):
> }{ // an empty block, so no value
undefined
> }!{ // !{} === false
false
> }!!{ // !!{} === true
true
> } +{ valueOf: function() { return 123; }
123
Related videos on Youtube
itchyny
Updated on June 04, 2022Comments
-
itchyny almost 2 years
In Google Chrome's console, when we input
(
and Enter, Chrome says "SyntaxError: Unexpected token }" Why? Input is just "(", including no "}".
We get the same error when we input
console.log(
There's no "}"!!!
Next token should be arguments list or ")" so error message should be "Expected arguments list" or "Unclosed (" or something.
And I wanna know, is console input parsed as
StatementList(opt)
(defined in ECMA-262)?-
BoltClock about 13 years@Seth: He did, it's just not easy to see.
-
-
Cameron about 13 years+1 for what amounts to clever SQL-injection with Javascript ;-) That
0
is most curious... -
itchyny about 13 yearsThanks for quick response. Hmm... It's very tricky... So Chrome seems to parse
'{' + text + '}'
. I tried}; '10 '+{
and get"10 [object Object]"
, which is the same result as Firefox. -
itchyny about 13 yearsWow! Great! I saw InjectedScriptSource.js line 280 to find exactly what you're saying! Thank you very much!
-
Joachim Sauer about 13 years@Cameron: it would be a JavaScript-injection attack then ;-)