Refresh/reload active browser tab from command line

browserchromecommand linefirefox

I'm trying to set up a custom toolchain where the browser (Firefox or, preferrably, Chrome) is often/frequently/constantly forced to refresh from the commandline.

(The idea is to instantly see the visual changes in the html/webapp I'm editing in an adjacent Emacs frame – without having to constantly tab to the browser to do a manual refresh.)

The closest I've come so far is to run google-chrome FILE_PATH. However this opens a new tab every time.

Are there other approaches?

Best Answer

Something to play with

It uses xdotool, which lets you script windows/desktop actions. If you supply the name of the browser as an argument, it'll find and reload the current page. You can set a default browser, so you don't need to supply one each time, and you can change whether you send a CTRL-R to reload, or SHIFT-CTRL-R to reload without cache.

It should flip to your browser, reload the page, then flip back to whatever window you called this from. I use this often by putting browser in background, with editor window set to 'ON-TOP' so it's always visible, hot-key this script, or call it from your editor, and it'll return your focus when it's done.

I'm a vim user, and I could see making an autocommand to automatically trigger this script whenever a given file was written, so the browser would refresh when appropriate, I know you can do the same.

#!/bin/bash
#
# L Nix <lornix@lornix.com>
# reload browser window
#
# whether to use SHIFT+CTRL+R to force reload without cache
RELOAD_KEYS="CTRL+R"
#RELOAD_KEYS="SHIFT+CTRL+R"
#
# set to whatever's given as argument
BROWSER=$1
#
# if was empty, default set to name of browser, firefox/chrome/opera/etc..
if [ -z "${BROWSER}" ]; then
    BROWSER=firefox
fi
#
# get which window is active right now
MYWINDOW=$(xdotool getactivewindow)
#
# bring up the browser
xdotool search --name ${BROWSER} windowactivate --sync
# send the page-reload keys (C-R) or (S-C-R)
xdotool search --name ${BROWSER} key --clearmodifiers ${RELOAD_KEYS}
#
# sometimes the focus doesn't work, so follow up with activate
xdotool windowfocus --sync ${MYWINDOW}
xdotool windowactivate --sync ${MYWINDOW}
#
Related Question