Pavlo
Pavlo

Reputation: 44889

How to evaluate a script in Chrome headless?

Node has -e and -p flags for evaluate and evaluate-and-print respectively. I know there is a --repl flag for Chrome headless, but I wonder is there a way to evaluate-and-print an expression as well, e.g:

$ chrome --headless --eval-and-print 'navigator.hardwareConcurrency'

Upvotes: 3

Views: 1285

Answers (2)

lossleader
lossleader

Reputation: 13495

The headless mode currently only supports:

  • printing/screenshots
  • dumping the dom
  • interaction by repl
  • interaction by remote debugger

If you don't want to work with the interactive modes or one of the wrappers around them and don't actually need to navigate to a page then you can use a data: url to provide javascript and get the output from dump-dom, for example:

chromium --headless --dump-dom 'data:text/html,<script>document.head.innerHTML="<code>\n"+navigator.hardwareConcurrency+"\n</code>"</script>' | grep -v 'code>'

Upvotes: 2

Hugues M.
Hugues M.

Reputation: 20467

Apparently it accepts to read from stdin, so this awful hack "works":

$ echo -e 'navigator.hardwareConcurrency\nquit\n' | chrome --headless --repl
[0412/235456.154837:ERROR:gpu_process_transport_factory.cc(980)] Lost UI shared context.
[0412/235456.214132:INFO:headless_shell.cc(370)] Type a Javascript expression to evaluate or "quit" to exit.
>>> {"result":{"description":"8","type":"number","value":8}}
>>> 

So, with more awful hacks and jq:

$ echo -e 'navigator.hardwareConcurrency\nquit\n' | chrome --headless --repl 2>&1 | grep '^>>> {"result":' | cut -c4- | jq -r .result.description
8

Upvotes: 5

Related Questions