Opening URLs in macOS in the default application

Created On:

While working on a project, I wanted to open a URL in the default browser on macOS. I was looking for a C API so I didn’t need to bridge with Objective-C or Swift code. I only cared about HTTP or HTTPS URLs.

The simplest solution I found is the LSOpenCFURLRef function from the LaunchServices framework. Within the macOS SDK the function is declared in the following header:

LaunchServices.framework/Versions/A/Headers/LSOpen.h

Quoting the header:

LSOpenCFURLRef()

Summary: Open an application, document, or folder.

Discussion: Opens applications, documents, and folders. Applications are opened via an ‘oapp’ or ‘rapp’ event. Documents are opened in their user-overridden or default applications as appropriate. Folders are opened in the Finder. Use the more specific LSOpenFromURLSpec for more control over launching.

Mac OS X threading: Thread safe since version 10.2

Parameters:

inURL: The CFURLRef of the item to launch.

outLaunchedURL: The CFURLRef of the item actually launched. For inURLs that are documents, outLaunchedURL will be the application used to launch the document. Can be NULL. THIS FUNCTION, DESPITE ITS NAME, RETAINS THE URL REFERENCE ON BEHALF OF THE CALLER. THE CALLER MUST EVENTUALLY RELEASE THE RETURNED URL REFERENCE.

Using the PyObjC library it’s pretty easy to play with:

import CoreFoundation
import LaunchServices

url = CoreFoundation.CFURLCreateWithString(None, "http://www.example.com", None)
LaunchServices.LSOpenCFURLRef(url, None)

The above code will open www.example.com in the default browser.

Interestingly it supports any URL scheme that has a registered handler. Running the following for example opens the Signal desktop app:

url = CoreFoundation.CFURLCreateWithString(None, "sgnl://", None)
LaunchServices.LSOpenCFURLRef(url, None)