Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webbrowser python open new url in same tab. Does this ever work?

It seems to me that Python's webbrowser 'new=0' functionality (see here), which opens a new url in the same tab or window, is not ever working.

The documentation uses dodgy language like "if possible" to mask this problem.

Has anyone seen any success with this functionality in the webbrowser module? Are there any known workarounds to achieve this functionality?


I have tried setting the webbrowser with

webbrowser.get(TYPE)

before continuing with opening urls. I have also tried using a slew of different browsers, however still have seen no success. Is this just not possible anymore? Should I just use selenium?


Among others, I have checked out this post from 7 years ago. I am hoping things have changed since then and people have found a way around this.

Any help or insight is much appreciated.

like image 492
Lamar Avatar asked Nov 08 '22 23:11

Lamar


1 Answers

I'm using MacOS and Chrome and ran into this. I noticed that for MacOS, webbrowser.py just builds a little applescript and opens the URL with the 'open location' command, e.g.,

script = 'open location "%s"' % url.replace('"', '%22') 

The built-in 'open location' command doesn't appear to support opening a url in an existing tab

I searched around in applescript examples and found that you can use commands from the Chrome applescript dictionary to open URL in the active tab like so:

tell application "Google Chrome"
    tell front window
        set URL of active tab to "www.google.com"
    end tell
end tell

I only needed to do this on a local project, so I just went with the dirty fix of overwriting the string in the 'script' variable to force it to use the latter format, like so:

# script = 'open location "%s"' % url.replace('"', '%22') 
script = '''tell application "Google Chrome"
    tell front window
        set URL of active tab to "%s"
    end tell
end tell ''' % url.replace('"', '%22')
like image 55
Stephen Allen Avatar answered Nov 14 '22 21:11

Stephen Allen