gpt4 book ai didi

macos - 在浏览器中打开 WebView URL

转载 作者:可可西里 更新时间:2023-11-01 01:05:39 24 4
gpt4 key购买 nike

我制作了一个非常简单的 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.
}
}
}

最佳答案

首先,将您的 WebView 的策略委托(delegate)和您的初始 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))
}

然后,覆盖委托(delegate)方法以拦截导航。

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
}
}

关于macos - 在浏览器中打开 WebView URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31033782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com