The following Python program uses the psutil module to get a list of processes that belong to you, checks if a known browser is running, and if so, start that one again. If no browser could be found, a default one is started. I've added some comments to clarify what's going on in the script.
Apart from the script itself, you'd still need to make this executable with chmod and make sure that the script is executed instead of launching a particular browser.
#!/usr/bin/env python
import psutil
import os
import subprocess
import sys
import pwd
def getlogin():
return pwd.getpwuid(os.geteuid()).pw_name
def start_browser(exe_path):
# Popen should start the process in the background
# We'll also append any command line arguments
subprocess.Popen(exe_path + sys.argv[1:])
def main():
# Get our own username, to see which processes are relevant
me = getlogin()
# Process names from the process list are linked to the executable
# name needed to start the browser (it's possible that it's not the
# same). The commands are specified as a list so that we can append
# command line arguments in the Popen call.
known_browsers = {
"chrome": [ "google-chrome-stable" ],
"chromium": [ "chromium" ],
"firefox": [ "firefox" ]
}
# If no current browser process is detected, the following command
# will be executed (again specified as a list)
default_exe = [ "firefox" ]
started = False
# Iterate over all processes
for p in psutil.process_iter():
try:
info = p.as_dict(attrs = [ "username", "exe" ])
except psutil.NoSuchProcess:
pass
else:
# If we're the one running the process we can
# get the name of the executable and compare it to
# the 'known_browsers' dictionary
if info["username"] == me and info["exe"]:
print(info)
exe_name = os.path.basename(info["exe"])
if exe_name in known_browsers:
start_browser(known_browsers[exe_name])
started = True
break
# If we didn't start any browser yet, start a default one
if not started:
start_browser(default_exe)
if __name__ == "__main__":
main()