Prevent universal links from opening in `WKWebView

2020-05-24 04:24发布

问题:

When user tap on a universal link in WKWebView, the corresponding app will be opened (if installed).

This is described in Apple Search Programming Guide

If you instantiate a SFSafariViewController, WKWebView, or UIWebView object to handle a universal link, iOS opens your website in Safari instead of opening your app. However, if the user taps a universal link from within an embedded SFSafariViewController, WKWebView, or UIWebView object, iOS opens your app.

In my app, I have a WKWebView, but I don't want the user to go out of my app. I want to handle the link within my WKWebView.

How do I prevent universal link from opening? Or can I know if a URL could be handle by other apps?

回答1:

sourcecode for WebKit:

static const WKNavigationActionPolicy WK_API_AVAILABLE(macosx(10.11), ios(9.0)) _WKNavigationActionPolicyAllowWithoutTryingAppLink = (WKNavigationActionPolicy)(WKNavigationActionPolicyAllow + 2);

if you are using WKWebView, just use WKNavigationActionPolicyAllow + 2 instead of WKNavigationActionPolicyAllow



回答2:

Base on @none 's answer, here is an example for Swift 4

I've tested it and it does work!

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    decisionHandler(WKNavigationActionPolicy(rawValue: WKNavigationActionPolicy.allow.rawValue + 2)!)
}


回答3:

+[LSAppLink openWithURL:completionHandler:] this is how universal link open corresponding app. you can exchange its implementations with yourself method but be carefule,this is private API.

you can check LSAppLink head file here



回答4:

Can you try this?

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    decisionHandler(WKNavigationActionPolicy(rawValue: WKNavigationActionPolicy.allow.rawValue + 2)!)
}