Process X11 Input – How to Send Keystrokes (F5) from Terminal to a GUI Program

inputprocessx11

I'm using a Raspberry Pi in combination with Chromium (kiosk mode) to show up some stats. The Pi doesn't have a connected keyboard so I searched for a solution to send keystrokes from the terminal to the Chromium (tab) process. Normal input does work but how do I send something like F5 (a special key: browser refresh) via this solution?

# pidof chromium
20809 20790 20788 20786 20783
# echo 'some text' > /proc/20809/fd/0

Best Answer

GUI programs don't read from their standard input, they get their input from the X server. There are tools to inject a keystroke to a window. xdotool is fairly common and convenient.

You'll need to find the window ID that you want to send the keystroke to. You can do that with xdotool. xdotool search --class Chrome returns the list of window IDs of all the Chrome windows. If this returns more than one, you need to pick the one you want. You can use xdotool search --name to match on the title instead of the class. You can also parse the output of wmctrl and extract the desired window ID.

Once you've found the right window ID, you can call xdotool to inject a keystroke. Unfortunately, many applications reject synthetic events, i.e. keystrokes and mouse events sent by another application. This is the case with current versions of Chrome. It's possible to inject a keystroke from another application by a different mechanism, but that requires the window to be focused. You can do all of that with xdotool, but it'll cause the focus to quickly flicker to the Chrome window and back. The following snippet sends F5 to the first Chrome window (in a somewhat arbitrary order).

xdotool search --class Chrome windowactivate --sync %1 key F5 windowactivate $(xdotool getactivewindow)

Or with older versions of xdotool:

xdotool windowactivate $(xdotool search --class Chrome) &&
xdotool key F5 &&
xdotool windowactivate $(xdotool getactivewindow)

Remember that this sends F5 to that window and it's up to the program to decide what to do with it. In Chrome, this reloads the current tab.

Related Question