Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get macOS default browser name - LSCopyDefaultApplicationURLForContentType

I am developing a macOS application in Xcode. One of the things I need to do, is to open URLs the system default web browser. I have an alert that pops up that gives the user this option. The alert is supposed to show the name of the default web browser. However I am unable to figure out the name of the default web browser.

I have the tried the following code:

NSLog(@"%@", LSCopyDefaultApplicationURLForContentType(kUTTypeURL, kLSRolesAll, nil));

It just returns file:///Applications/Opera.app/ even though my default browser is set to Safari. Not matter what I change my default browser to (Chrome, Safari, Firefox, etc...), the above method just returns the URL for Opera browser.

How can I find out what the name of the default browser is? I know how to open URLs in the default browser, that's very easy, but getting the name of the default browser isn't.

I know this is possible because apps like Tweetbot, have an option saying "Open in Safari" which changes to whatever you default browser is.

like image 544
Supertecnoboff Avatar asked Mar 23 '26 08:03

Supertecnoboff


2 Answers

You can use [[NSWorkspace sharedWorkspace] open:url] to open any URL in the default browser and [[NSWorkspace sharedWorkspace] URLForApplicationToOpenURL: url] to get the URL for the default application for a given URL.

To get the app name, try [[NSBundle bundleWithURL:appUrl] objectForInfoDictionaryKey:@"CFBundleDisplayName"] or [[NSBundle bundleWithURL:appUrl] objectForInfoDictionaryKey:@"CFBundleName"] if the first is null. If both fail, [appUrl deletingPathExtension] lastPathComponent] can be used as a last resort.

See the docs here:

https://developer.apple.com/documentation/appkit/nsworkspace/1533463-openurl?language=objc

https://developer.apple.com/documentation/appkit/nsworkspace/1533391-urlforapplicationtoopenurl?language=objc

https://developer.apple.com/documentation/foundation/nsbundle/1408696-objectforinfodictionarykey?language=objc

like image 170
Matusalem Marques Avatar answered Mar 24 '26 22:03

Matusalem Marques


Try the other LaunchServices method LSCopyDefaultApplicationURLForURL and pass the http scheme

CFURLRef httpURL = CFURLCreateWithString(kCFAllocatorDefault, CFSTR("http://"), NULL);
NSLog(@"%@", LSCopyDefaultApplicationURLForURL(httpURL, kLSRolesAll, nil));
like image 25
vadian Avatar answered Mar 24 '26 20:03

vadian