简体   繁体   中英

Prevent universal links from opening in `WKWebView`/`UIWebView`

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?

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

+[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

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

Can you try this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM