Cocoa浏览器:如何让target_blank链接在新标签页打开?
解决Cocoa浏览器中target_blank链接在新标签页打开的问题
我来帮你搞定这个问题!你之前遇到的错误是因为newWindowForTab是一个IBAction方法,调用时参数传递逻辑不对,更关键的是WKNavigationDelegate的createWebViewWith方法需要返回对应的WKWebView实例,让系统明确知道用哪个WebView来处理新窗口的请求。
第一步:调整窗口控制器的newWindowForTab方法
先修改WindowController里的方法,让它能返回新创建的窗口控制器,方便我们后续获取里面的WebView:
@IBAction override func newWindowForTab(_ sender: Any?) -> WindowController? { guard let storyboard = self.storyboard else { return nil } let newWindowController = storyboard.instantiateInitialController() as! WindowController let newWindow = newWindowController.window! newWindow.windowController = self self.window!.addTabbedWindow(newWindow, ordered: .above) return newWindowController }
第二步:正确实现WKNavigationDelegate的导航方法
接下来在你的ViewController里,修改createWebViewWith方法,逻辑是:遇到target_blank的请求时,创建新标签,拿到新标签的WebView,加载请求并返回这个WebView:
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { // 只处理targetFrame为nil的情况(对应target_blank的链接) guard navigationAction.targetFrame == nil else { return nil } // 获取当前窗口控制器,并创建新标签 guard let currentWindowController = self.view.window?.windowController as? WindowController, let newWindowController = currentWindowController.newWindowForTab(nil) else { return nil } // 获取新标签对应的ViewController和它的WebView(这里假设你的WebView的IBOutlet名为webView) guard let newViewController = newWindowController.contentViewController as? ViewController else { return nil } // 在新标签的WebView中加载目标请求 newViewController.webView.load(navigationAction.request) // 返回新的WebView,让WKWebView明确用这个实例处理新窗口的导航 return newViewController.webView }
为什么之前的代码会报错?
你之前的代码newWindowForTab(webView.load(navigationAction.request))存在两个核心问题:
webView.load()返回的是WKNavigation?,传递给newWindowForTab属于无效参数,逻辑完全不对;createWebViewWith方法要求返回WKWebView?,但你直接返回nil,系统找不到对应的新WebView实例,只能退而求其次在当前页面加载请求。
现在的代码逻辑就通顺了:当触发target_blank链接时,主动创建新标签,把请求加载到新标签的WebView里,同时返回这个WebView给WKWebView,让它正确处理新窗口的导航行为。
内容的提问来源于stack exchange,提问作者Won ixer
相关产品推荐
相关产品推荐

