Tuesday, October 4, 2022

[SOLVED] Get the "user agent" string from a new Google Chrome browser session from bash

Issue

I want to get the User Agent HTTP request header string from a new Google Chrome browser session (just opened) from bash and put it in a variable.

Here is the pseudo-code:

USER_AGENT="$(google-chrome --user-agent)"
echo "$USER_AGENT"

Output example:

Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

If it is not possible to do this with the google-chrome command, what is an equivalent workaround?


Solution

Chrome in headless mode with the --repl command line option evaluates Javascript expressions. You could try something like the following to get the user agent string:

echo navigator.userAgent | /opt/google/chrome/chrome --headless --repl 2> /dev/null | sed 's/^>>> //' | jq -r .result.value

Note: Do run the chrome binary (e.g. /opt/google/chrome/chrome) directly rather than the google-chrome shell script, because it seems that the shell script does not support passing the standard input through.

The sed command removes the prompt from the output and the jq command extracts the value from the JSON string that Chrome prints.

Note however that the user agent string when running Chrome with the --headless command line flag is not identical to the user agent string when running it regularly. At least Chrome 105 seems to have "HeadlessChrome" instead of "Chrome".



Answered By - Jukka Matilainen
Answer Checked By - Marilyn (WPSolving Volunteer)