Skip to content Skip to sidebar Skip to footer

How To Get A Name Of Default Browser Using Python

My script runs a command every X seconds. If a command is like 'start www' -> opens a website in a default browser I want to be able to close the browser before next time the co

Solution 1:

The solution is going to differ from OS to OS. On Windows, the default browser (i.e. the default handler for the http protocol) can be read from the registry at:

HKEY_CURRENT_USER\Software\Classes\http\shell\open\command\(Default)

Python has a module for dealing with the Windows registry, so you should be able to do:

from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValue
# In Py3, this module is called winreg without the underscore

with OpenKey(HKEY_CURRENT_USER,
             r"Software\Classes\http\shell\open\command") as key:
    cmd = QueryValue(key, None)

You'll get back a command line string that has a %1 token in it where the URL to be opened should be inserted.

You should probably be using the subprocess module to handle launching the browser; you can retain the browser's process object and kill that exact instance of the browser instead of blindly killing all processes having the same executable name. If I already have my default browser open, I'm going to be pretty cheesed if you just kill it without warning. Of course, some browsers don't support multiple instances; the second instance just passes the URL to the existing process, so you may not be able to kill it anyway.


Solution 2:

I would suggest this. Honestly Python should include this in the webbrowser module that unfortunately only does an open bla.html and that breaks anchors on the file:// protocol.

Calling the browser directly however works:

    # Setting fallback value
browser_path = shutil.which('open')

osPlatform = platform.system()

if osPlatform == 'Windows':
    # Find the default browser by interrogating the registry
    try:
        from winreg import HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, OpenKey, QueryValueEx

        with OpenKey(HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice') as regkey:
            # Get the user choice
            browser_choice = QueryValueEx(regkey, 'ProgId')[0]

        with OpenKey(HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(browser_choice)) as regkey:
            # Get the application the user's choice refers to in the application registrations
            browser_path_tuple = QueryValueEx(regkey, None)

            # This is a bit sketchy and assumes that the path will always be in double quotes
            browser_path = browser_path_tuple[0].split('"')[1]

    except Exception:
        log.error('Failed to look up default browser in system registry. Using fallback value.')

Post a Comment for "How To Get A Name Of Default Browser Using Python"