If you’ve worked at a place that uses Outlook for email or Chrome for browsers, knowing is half the battle when it comes to helping out your users. For a long while you could easily determine the URL scheme handlers via the built-in Python or JXA, however things have changed.
For example this JXA used to work brilliantly in Mojave and under:
#!/bin/sh
URLScheme="${1}"
if [ -z "${URLScheme}" ]; then
echo "Please provide a URL scheme name"
exit 1
fi
osascript -l JavaScript <<< "ObjC.import('Cocoa'); $.LSCopyDefaultHandlerForURLScheme(\"${URLScheme}\")"
Nothing lasts forever though and all that broke in 10.15 when the result of [object Ref]
became the taunting reply. Even if you could hit the juke box like the Fonz and recast the CF value you were getting back into an NS value (thanks for the link Pico), it was a moot point by Big Sur. Apple has killed off about every useful API to figure out what app handles a URL as others have noted.
So after you look at LSCopyDefaultHandlerForURLScheme at the Dev Docs and then see the scores of other deprecated LaunchServices functions, you might make some joke like “I see dead people APIs” (a la Sixth Sense), but still you wonder: Is there a reliable way to divine this information without resorting to a hacky grep?
Why, yes there is, and it just so happens to use my tool ljt too! While definitely a step up from grepping the output it’s still kinda sad. What was once a few lines must now be accomplished by many more in getDefaultRoleHandler.sh and the minified version getDefaultRoleHandler.min.sh.
#!/bin/sh
: <<-LICENSE_BLOCK
getDefaultRoleHandler - (https://github.com/brunerd)
Copyright (c) 2022 Joel Bruner (https://github.com/brunerd)
Licensed under the MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
LICENSE_BLOCK
#############
# FUNCTIONS #
#############
#use this self-contained function in your script to detect the default role handle
function getDefaultRoleHandler() (
#provide a URL scheme like: http, https, ftp, etc...
URLScheme=${1}
#fail quickly
if [ -z "${URLScheme}" ]; then
>/dev/stderr echo "No URL scheme specified"
return 1
fi
#Little JSON Tool (ljt) v1.0.7 - https://github.com/brunerd/ljt - MIT License
function ljt () (
[ -n "${-//[^x]/}" ] && set +x; read -r -d '' JSCode <<-'EOT'
try{var query=decodeURIComponent(escape(arguments[0])),file=decodeURIComponent(escape(arguments[1]));if("/"===query[0]||""===query){if(/~[^0-1]/g.test(query+" "))throw new SyntaxError("JSON Pointer allows ~0 and ~1 only: "+query);query=query.split("/").slice(1).map(function(a){return"["+JSON.stringify(a.replace(/~1/g,"/").replace(/~0/g,"~"))+"]"}).join("")}else if("$"===query[0]||"."===query[0]||"["===query[0]){if(/[^A-Za-z_$\d\.\[\]'"]/.test(query.split("").reverse().join("").replace(/(["'])(.*?)\1(?!\\)/g,"")))throw Error("Invalid path: "+query);}else query=query.replace("\\.","\udead").split(".").map(function(a){return"["+JSON.stringify(a.replace("\udead","."))+"]"}).join("");"$"===query[0]&&(query=query.slice(1,query.length));var data=JSON.parse(readFile(file));try{var result=eval("(data)"+query)}catch(a){}}catch(a){printErr(a),quit()}void 0!==result?null!==result&&result.constructor===String?print(result):print(JSON.stringify(result,null,2)):printErr("Path not found.");
EOT
queryArg="${1}"; fileArg="${2}";jsc=$(find "/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/" -name 'jsc');[ -z "${jsc}" ] && jsc=$(which jsc);[ -f "${queryArg}" -a -z "${fileArg}" ] && fileArg="${queryArg}" && unset queryArg;if [ -f "${fileArg:=/dev/stdin}" ]; then { errOut=$( { { "${jsc}" -e "${JSCode}" -- "${queryArg}" "${fileArg}"; } 1>&3 ; } 2>&1); } 3>&1;else [ -t '0' ] && echo -e "ljt (v1.0.7) - Little JSON Tool (https://github.com/brunerd/ljt)\nUsage: ljt [query] [filepath]\n [query] is optional and can be JSON Pointer, canonical JSONPath (with or without leading $), or plutil-style keypath\n [filepath] is optional, input can also be via file redirection, piped input, here doc, or here strings" >/dev/stderr && exit 0; { errOut=$( { { "${jsc}" -e "${JSCode}" -- "${queryArg}" "/dev/stdin" <<< "$(cat)"; } 1>&3 ; } 2>&1); } 3>&1; fi;if [ -n "${errOut}" ]; then /bin/echo "$errOut" >&2; return 1; fi
)
#in case being run as root get the current console user
consoleUserHomeFolder=$(sudo -u "$(stat -f %Su /dev/console)" sh -c 'echo ~')
#get the LaunchServices LSHandlers JSON of the console user
launchServicesJSON=$(launchctl asuser "$(stat -f %u /dev/console)" sudo -u "$(stat -f %Su /dev/console)" plutil -extract LSHandlers json -o - "${consoleUserHomeFolder}"/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist)
#loop through JSON and try and find matching URLScheme within
for ((i=0;;i++)); do
#if we are at the END of the array or nothing exists bail
if ! ljt "/$i" <<< "${launchServicesJSON}" &>/dev/null; then
return 1
elif [ "$(ljt "/$i/LSHandlerURLScheme" <<< "${launchServicesJSON}" 2>/dev/null)" = "$URLScheme" ]; then
#run query, print result, errors go to /dev/null, if ljt fails to find something return non-zero
if ! ljt "/$i/LSHandlerRoleAll" <<< "${launchServicesJSON}" 2>/dev/null; then
#error
return 1
else
#success
return 0
fi
fi
done
#if we are here, we did NOT find a match
return 1
)
########
# MAIN #
########
getDefaultRoleHandler "$@"
We use plutil
to extract the contents of the LSHandlers
key as JSON from ~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist
then we iterate over the array using a for
loop and ljt
until it finds a matching LSHandlerURLScheme
and then it prints out the value of LSHandlerRoleAll
. The operation and output are simple and no nonsense. Give it a URL scheme and it gives you the Bundle ID of the app which will open it or if not found, nothing. (Note: mailto
will be blank by default, only after switching to another client will it return a result)
You can use this function in your scripts. Head over to my GitHub to download either getDefaultRoleHandler.sh or the minified getDefaultRoleHandler.min.sh. Perhaps you need to alert a user to change their application preferences after installation of an email client or web browser. You can use my shui function to alert them, btw. But I’m not getting into setting handlers via script in this post, writing to the plist can be a trick but the real trick is getting LaunchService to read from that plist (without asking for a reboot or logout, ick)! So for now “Knowing Is Half The Battle™”
Post Posting Update
Armin Briegel, over at the wonderful wealth of aggregated MacAdmin knowledge that is scriptingosx.com, is always kind enough to post my articles and this very one appears in the Week of 2022-09-22. Along with this post is a link to a MacAdmins Slack thread where he kindly provided some JXA that returns the file path for a URL scheme handler (vs. the above Bundle ID), then Pico jumped in and crushed it down to a 1 liner! I’ve added the thinnest of function wrappers over top:
#!/bin/sh
#getDefaultRoleHandlerPath - Joel Bruner with 🙏 thanks to a couple stalwarts of the MacAdmin Slack Armin Briegel and Pico
function getDefaultRoleHandlerPath()(urlScheme="${1}"; [ -z "${urlScheme}" ] && return 1; osascript -l 'JavaScript' -e "ObjC.import('AppKit'); $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString('${urlScheme}:')).path.js")
getDefaultRoleHandlerPath "$@"
exit $?
So it seems Apple has spared an API in AppKit’s NSWorkspace by the name of URLForApplicationToOpenURL
, which has been around since macOS 10.6! Perhaps when I get over my trust issues with JXA, I’ll explore these APIs to see what else might be useful. For now though this does the trick of returning a filepath (not Bundle ID)
Listing All Schemes for User
I got a question about listing all the schemes a user might have registered. This is an example one-liner (granted jpt is embedded in the script or installed locally) to be run by the current user. If you want to run as root, cannibalize getDefaultRoleHandler.sh for code)
jpt -T '$.*.LSHandlerURLScheme' <<< $(plutil -extract LSHandlers json -o - ~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist)
The -T
option will output text (vs. an array of double quoted JSON strings) .*
looks at every array member to print out every LSHandlerURLScheme entry for the current console user. It’ll look something like this