在macOS的默认浏览器中打开WKWebview Open target =“ _ blank”链接

时间:2019-04-03 22:51:39

标签: swift macos wkwebview

我正在尝试使用Xcode的Swift Code在MacOS的默认浏览器中打开WKWebview打开外部链接(target = _blank)。此代码仅用于下载zip或nzb链接文件,并且不起作用:

尝试

func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
    let url = request.URL!.absoluteString
    if url.hasSuffix(".zip") || url.hasSuffix(".nzb") {
        listener.ignore()
        NSWorkspace.sharedWorkspace().openURL(request.URL!)
    } else {
        listener.use()
    }
}

该代码不适用于macosx 10.14和webview上的Webview应用程序,而WebPolicyDecisionListener已弃用10.14。

我希望WKWebview使用Swift打开外部链接(target = _blank)。

1 个答案:

答案 0 :(得分:0)

您需要将webView.uiDelegate = ...分配给WKUIDelegate和实例,然后处理createWebViewWith:for:windowFeatures:;例如

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if let url = navigationAction.request.url, navigationAction.targetFrame == nil {
        let shared = UIApplication.shared
        if shared.canOpenURL(url) {
            shared.open(url, options: [UIApplication.OpenExternalURLOptionsKey: Any](), completionHandler: nil)
        }
    }
    return nil;
}