I would like to know a way to open the default browser on OS X from a C++ application and then open a requested URL.
EDIT: I solved it like this:
system("open http://www.apple.com");
From the Apple menu in the corner of your screen, choose System Preferences. Click General. Choose a web browser from the “Default web browser” menu.
Safari is the default browser when you first set up your Mac. If you accidentally change your default browser or just want to change it back to Safari, you can easily adjust your default. On your Mac, choose Apple menu > System Settings, then click Desktop & Dock in the sidebar. (You may need to scroll down.)
Press Command + Option + esc and Force Quit System Preferences. After that, follow the steps to change the default browser again. Click and restart the Mac. Now retry and you should see the browser as a list of potential default options in System Preferences.
Select the Start button, and then type Default apps. In the search results, select Default apps. Under Web browser, select the browser currently listed, and then select Microsoft Edge or another browser.
In case you prefer using the native OS X APIs instead of system("open ...")
You can use this code:
#include <string>
#include <CoreFoundation/CFBundle.h>
#include <ApplicationServices/ApplicationServices.h>
using namespace std;
void openURL(const string &url_str) {
CFURLRef url = CFURLCreateWithBytes (
NULL, // allocator
(UInt8*)url_str.c_str(), // URLBytes
url_str.length(), // length
kCFStringEncodingASCII, // encoding
NULL // baseURL
);
LSOpenCFURLRef(url,0);
CFRelease(url);
}
int main() {
string str("http://www.example.com");
openURL(str);
}
Which you have to compile with the proper OS X frameworks:
g++ file.cpp -framework CoreFoundation -framework ApplicationServices
Look at the docs for Launch Services.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With