Skip to content

Instantly share code, notes, and snippets.

@TylerLeonhardt
Last active June 2, 2021 08:43
Show Gist options
  • Save TylerLeonhardt/529adf6d3f392d86560145c7201e5d87 to your computer and use it in GitHub Desktop.
Save TylerLeonhardt/529adf6d3f392d86560145c7201e5d87 to your computer and use it in GitHub Desktop.
Get and Set the default browser on macOS. Also is an example at how to leverage other scripting languages within PowerShell
# NOTE: This still pops a dialog... I can't seem to figure out how to -Force it to not show.
function Set-DefaultBrowser {
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
$BrowserId
)
$pythonScript = @"
from LaunchServices import LSSetDefaultHandlerForURLScheme
from LaunchServices import LSSetDefaultRoleHandlerForContentType
# 0x00000002 = kLSRolesViewer
# see https://developer.apple.com/library/mac/#documentation/Carbon/Reference/LaunchServicesReference/Reference/reference.html#//apple_ref/c/tdef/LSRolesMask
LSSetDefaultRoleHandlerForContentType(\"public.html\", 0x00000002, \"$BrowserId\")
LSSetDefaultRoleHandlerForContentType(\"public.xhtml\",0x00000002, \"$BrowserId\")
LSSetDefaultHandlerForURLScheme(\"http\", \"$BrowserId\")
LSSetDefaultHandlerForURLScheme(\"https\", \"$BrowserId\")
"@
if($PSCmdlet.ShouldProcess("Running Python script", $pythonScript)) {
python -c $pythonScript
}
}
function Get-DefaultBrowser {
[CmdletBinding(SupportsShouldProcess = $true)]
param()
$appleScriptPath = "$PSScriptRoot/GetDefaultBrowser.scpt"
if($PSCmdlet.ShouldProcess("Running AppleScript script", (Get-Content -Raw $appleScriptPath))) {
osascript $appleScriptPath
}
}
#!/usr/bin/osascript
# Idk what this is but Stack Overflow said so
tell (system attribute "sysv") to set MacOS_version to it mod 4096 div 16
if MacOS_version is 5 then
set {a1, a2} to {1, 2}
else
set {a1, a2} to {2, 1}
end if
set pListpath to (path to preferences as Unicode text) & "com.apple.LaunchServices:com.apple.launchservices.secure.plist"
tell application "System Events"
set launchServicesPList to property list file pListpath
repeat with i in property list items of property list item 1 of contents of launchServicesPList
if value of property list item a2 of i is in {"http", "https", "public.html", "public.xhtml"} then
return the value of the property list item a1 of i
end if
end repeat
end tell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment