pythonpython-webbrowser

Python Webbrowser not opening new window


From what I am reading Python webbrowser documentation you can either use Open() with a new=1 argument or using open_new() should open a new window. Not another tab.

I was working on a bigger project where I needed this functionality. Thought it was something else in the code and slimmed it down to this:

import webbrowser
webbrowser.open("https://stackoverflow.com", new=1, autoraise=True)
webbrowser.open_new("https://stackoverflow.com")

Even with just these 3 lines of code, the problem persist, both of the different functions should open it in a new window. But non of them does it.

Does anyone know why it opens it in a tab rather than a new window?


Solution

  • In this case, I'm going to look at a copy of the webbrowser.py code, as present on my local system (python 3.13). It will, by default, on windows, attempt to use the following code to launch a browser:

    if sys.platform[:3] == "win":
        class WindowsDefault(BaseBrowser):
            def open(self, url, new=0, autoraise=True):
                sys.audit("webbrowser.open", url)
                try:
                    os.startfile(url)
                except OSError:
                    # [Error 22] No application is associated with the specified
                    # file for this operation: '<URL>'
                    return False
                else:
                    return True
    

    i.e. it completely ignores new and autoraise. The code in question uses os.startfile, without any parameters.

    The long and short of this code is that new and autoraise don't do anything if it successfully invokes the default url handler registered on Windows.

    Almost all other browsers on Windows are passed through a BackgroundBrowser class, which does the following:

    class BackgroundBrowser(GenericBrowser):
        """Class for all browsers which are to be started in the
           background."""
    
        def open(self, url, new=0, autoraise=True):
            cmdline = [self.name] + [arg.replace("%s", url)
                                     for arg in self.args]
            sys.audit("webbrowser.open", url)
            try:
                if sys.platform[:3] == 'win':
                    p = subprocess.Popen(cmdline)
                else:
                    p = subprocess.Popen(cmdline, close_fds=True,
                                         start_new_session=True)
                return p.poll() is None
            except OSError:
                return False
    

    again, looking at the code, we see that it completely ignores new and autoraise.

    There does appear to be a lot better support on Unix/Linux for the flags, so unfortunately it looks like you're not going to get it to do what you want with the currently implemented code.