#!/bin/bash # this script will set the current default application for a url scheme # by Armin Briegel - Scripting OS X # IMPORTANT: when changing default app for 'http' user is prompted # also 'https' will be automatically set when 'http' is changed # attempting to change 'https' will result in an error # Permission is granted to use this code in any way you want. # Credit would be nice, but not obligatory. # Provided "as is", without warranty of any kind, express or implied. # get data from arguments # when running as a Jamf policy, first three args with be target volume, # computer name and user name. Target volume will always be `/`, unless # you are imaging, which is dead... # Then we shift the first three args. That way we can run interactively # from Terminal as well as from a Jamf policy. if [[ "$1" == "/" ]]; then shift 3 fi urlScheme=${1?:"argument urlScheme required, e.g. 'http'"} identifier=${2?:"argument bundle identifier required, e.g. 'com.apple.safari'"} # you can get the identifier for an app with: # mdls /Applications/Firefox.app -name kMDItemCFBundleIdentifier -raw currentUser=$( echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }' ) uid=$(id -u "$currentUser") # global check if there is a user logged in if [[ -z "$currentUser" || "$currentUser" = "loginwindow" ]]; then echo "no user logged in, cannot proceed" exit 1 fi # now we know a user is logged in # run a command as the current user runAsUser() { if [ "$currentUser" != "loginwindow" ]; then launchctl asuser "$uid" sudo -u "$currentUser" "$@" fi } setDefaultAppForScheme() { local urlScheme=${1?:"arg 1 required: url scheme "} local bundleIdentifier=${2?:"arg 2 required: bundle identifier"} runAsUser osascript -l JavaScript << EndOfScript // create NSURL from scheme string const url = $.NSURL.URLWithString(ObjC.wrap("${urlScheme}:")) if ($.NSProcessInfo.processInfo.isOperatingSystemAtLeastVersion({majorVersion: 12, minorVersion: 0, patchVersion: 0})) { // macOS 12 and higher, use new NSWorkspace API ObjC.import("AppKit") const ws=$.NSWorkspace.sharedWorkspace const appURL = ws.URLForApplicationWithBundleIdentifier(ObjC.wrap("$bundleIdentifier")) ws.setDefaultApplicationAtURLToOpenURLsWithSchemeCompletionHandler(appURL, ObjC.wrap("$urlScheme"), err => {} ) delay(1) } else { // macOS 11 and earlier use deprecated LaunchServices API ObjC.import("LaunchServices") $.LSSetDefaultHandlerForURLScheme(ObjC.wrap("$urlScheme"), ObjC.wrap("$bundleIdentifier")) } EndOfScript } setDefaultAppForScheme "$urlScheme" "$identifier"