Skip to content

Commit 5892149

Browse files
committed
webbrowser: lookup default webbrowser on mac
ensures web browser is launched on mac, even for URLs that are not http[s].
1 parent 55f8bac commit 5892149

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

Lib/webbrowser.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,32 @@ def open(self, url, new=0, autoraise=True):
597597
sys.audit("webbrowser.open", url)
598598
url = url.replace('"', '%22')
599599
if self.name == 'default':
600-
script = f'open location "{url}"' # opens in default browser
600+
proto, _sep, _rest = url.partition(":")
601+
if _sep and proto.lower() in {"http", "https"}:
602+
# default web URL, don't need to lookup browser
603+
script = f'open location "{url}"'
604+
else:
605+
# if not a web URL, need to lookup default browser to ensure a browser is launched
606+
# this should always work, but is overkill to lookup http handler
607+
# before launching http
608+
script = f"""
609+
use framework "AppKit"
610+
use AppleScript version "2.4"
611+
use scripting additions
612+
613+
property NSWorkspace : a reference to current application's NSWorkspace
614+
property NSURL : a reference to current application's NSURL
615+
616+
set http_url to NSURL's URLWithString:"https://python.org"
617+
set browser_url to (NSWorkspace's sharedWorkspace)'s ¬
618+
URLForApplicationToOpenURL:http_url
619+
set app_path to browser_url's relativePath as text -- NSURL to absolute path '/Applications/Safari.app'
620+
621+
tell application app_path
622+
activate
623+
open location "{url}"
624+
end tell
625+
"""
601626
else:
602627
script = f'''
603628
tell application "{self.name}"
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Ensure web browser is launched by {func}`webbrowser.open` on macOS, even for
2+
``file://`` URLs.

0 commit comments

Comments
 (0)