Refresh Browser on save with inotify and xdotool

The following code is a simple solution to refresh a browser window when you save a file. It could be used with any editor and browser. It is based on Inotify for file system monitoring and xdodool to send fake keyboard input events.

#!/bin/bash
FILE=$1
BROWSER=google-chrome

$BROWSER $FILE

while [ 1 -eq 1 ]; do
    inotifywait -q $FILE >/dev/null
    echo "$(date --rfc-3339=seconds) Refresh: $FILE"
    CUR_WID=$(xdotool getwindowfocus)
    
    #gets the first $BROWSER window, if you have more than one
    #$BROWSER window open, it might not refresh the right one,
    #as an alternative you can search by the window/html title
    WID=$(xdotool search --onlyvisible --class $BROWSER|head -1)
    #TITLE="window/html file title"
    #WID=$(xdotool search --title "$TITLE"|head -1)
    xdotool windowactivate $WID
    xdotool key 'ctrl+r'
    xdotool windowactivate $CUR_WID
done

If you run Ubuntu, you need to install the following packages:

inotify-tools
xdotool