Open web browser URL in browser

I made a very simple Swift application that loads a web page with links to it. Whenever I click links, they do not open. How do I access links on a downloaded .html webpage 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() { super.viewDidLoad() let urlString = "URL" self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!)) } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } } 
+1
source share
2 answers

First set the WebView policy WebView and your start URL as a class variable:

 let url = NSURL(string: "http://www.google.com/")! // ... override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.webView.policyDelegate = self self.webView.mainFrame.loadRequest(NSURLRequest(URL: self.url)) } 

Then override 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 } } 
+1
source

You can also decide which links to open in WebView and what - in the browser is as simple as writing a target attribute on your html page, for example

 <a href="http://www.google.com/" target="_blank">external page</a> 

And use target verification in the PolicyForNewWindowAction solution mentioned above. I put the full answer in the thread of this question . Hope you can translate it to speed up.

0
source

All Articles