4

I am trying to open a url in Safari even if my default browser is set to Google Chrome. How do I do that? I am using the following code, but it opens the url in the default browser only.

let requiredURL = URL(string: "https://www.google.com)")!
NSWorkspace.shared.open(requiredURL)

Do I have to use the following function:

NSWorkspace.shared.open(urls: [URL], withApplicationAt: URL, options: NSWorkspace.LaunchOptions, configuration: [NSWorkspace.LaunchConfigurationKey : Any])

If so, how do I implement it?

3
  • i have found what you are looking for not the best approch but it will help you out stackoverflow.com/a/57496854/10585521 Nov 17, 2020 at 6:21
  • the shell process works except that it only opens the host url. For example, if i am trying to search something on google, the url should open the search result. However, using this method, it only manages to open www.google.com. Not the search within google. Nov 17, 2020 at 6:57
  • what i the link you want to open ? is there a chance you are are providing the wrong url ? Nov 17, 2020 at 7:06

1 Answer 1

1

You can use NSWorkspace open method which has been deprecated in macOS 11

let url = URL(string: "https://www.google.com")!

NSWorkspace.shared.open([url], withAppBundleIdentifier: "com.apple.safari", options: .default, additionalEventParamDescriptor: nil, launchIdentifiers: nil)

Or the replacement method (macOS 10.15 or later)

do {
    let safariURL = try FileManager.default.url(for: .applicationDirectory, in: .localDomainMask, appropriateFor: nil, create: false).appendingPathComponent("Safari.app")
    NSWorkspace.shared.open([url], withApplicationAt: safariURL, configuration: .init()) { (runningApp, error) in
        print("running app", runningApp ?? "nil")
    }
} catch {
    print(error)
}
   
1
  • This solution works fine except that it sometimes opens the link in a new tab and sometimes in a new window entirely. Is there any way to open in a new tab only? Nov 30, 2020 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.