Matthew Matthew - 7 months ago 84
Swift Question

Open WebView URL in Browser

I made a very simple Swift application that loads a webpage with links on it. Whenever I click the links, they do not open. How would I got about having the links on the loaded .html webpage open in a browser window for OS X?

Here is my implementation:

import Cocoa
import WebKit

class ViewController: NSViewController {

@IBOutlet weak var webView: WebView!

override func viewDidLoad() {
let urlString = "URL"
self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))

override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.

Answer Source

First, set your WebView's policy delegate and your initial URL as a class variable:

let url = NSURL(string: "")!

// ...

override func viewDidLoad() {

    // Do any additional setup after loading the view.

    self.webView.policyDelegate = self

    self.webView.mainFrame.loadRequest(NSURLRequest(URL: self.url))

Then, override the delegate methods to intercept navigation.

override func webView(webView: WebView!, decidePolicyForNewWindowAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, newFrameName frameName: String!, decisionListener listener: WebPolicyDecisionListener!) {
    println(__LINE__) // the method is needed, the println is for debugging

override func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
    if request.URL!.absoluteString == self.url.absoluteString { // load the initial page
        listener.use() // load the page in the app
    } else { // all other links
        NSWorkspace.sharedWorkspace().openURL(request.URL!) // take the user out of the app and into their default browser
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download