moka
moka

Reputation: 4491

C++ OS X open default browser

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");

Upvotes: 8

Views: 6069

Answers (2)

Alex Jasmin
Alex Jasmin

Reputation: 39496

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

Upvotes: 19

pmr
pmr

Reputation: 59811

Look at the docs for Launch Services.

Upvotes: 1

Related Questions