我制作了一个非常简单的Swift应用程序,它加载了一个带有链接的网页。每当我点击链接时,它们都不会打开。如何在OS X的浏览器窗口中打开已加载的.html网页上的链接?
这是我的实施:
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.
}
}
}
答案 0 :(得分:4)
首先,将WebView
的策略委托和初始URL设置为类变量:
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))
}
然后,覆盖委托方法以拦截导航。
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 :(得分:-1)
您还可以决定在WebView中打开哪些链接以及在浏览器中使用哪种链接就像在HTML页面中编写目标属性一样简单
<a href="http://www.google.com/" target="_blank">external page</a>
并在上面提到的decisionPolicyForNewWindowAction中使用目标检查。我在this question帖子中给出了完整的答案。希望你能把它翻译成快速的。