8

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");
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
moka
  • 4,353
  • 2
  • 37
  • 63

2 Answers2

19

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
Alex Jasmin
  • 39,094
  • 7
  • 77
  • 67
1

Look at the docs for Launch Services.

pmr
  • 58,701
  • 10
  • 113
  • 156