Skip to content

Instantly share code, notes, and snippets.

@kevenbauke
Last active June 21, 2022 17:13
Show Gist options
  • Save kevenbauke/d449718a5f268ee843f286db88f137cc to your computer and use it in GitHub Desktop.
Save kevenbauke/d449718a5f268ee843f286db88f137cc to your computer and use it in GitHub Desktop.
WKWebView open links in Safari
@knoxOnline
Copy link

knoxOnline commented Mar 19, 2021

Hi, is there a way to adapt this so it only opens URLs with target="_blank" externally?

Thanks.

@kevenbauke
Copy link
Author

kevenbauke commented Mar 19, 2021

Hi @knowOnline thanks for your question. There is a possibility. You just need to check for the targetFrame of the navigationAction before you call UIApplication.shared.open(url).

if navigationAction.targetFrame == nil {
	UIApplication.shared.open(url)
	decisionHandler(.cancel)
} else {
	decisionHandler(.allow)
}

@Miztra
Copy link

Miztra commented Nov 19, 2021

Im getting error with this when pressing a link.

Completion handler passed to -[test.pr webView:decidePolicyForNavigationAction:decisionHandler:] was called more than once

@kevenbauke
Copy link
Author

@Miztra cup that is fixed now. I removed the changes that were causing the error to appear.

@raymond-1227
Copy link

Hi, how do I check for URLs and application magnet links? My web application needs to launch another application via magnet links but the following code will handle links other than the default webview URL to open in browser or either just ignore. Thanks.

@kevenbauke
Copy link
Author

@raymond-1227 if you want want to detect magnet-links you can use a similar approach as how this code detects the links. You can use the scheme attribute of the URLComponent.

if components?.scheme == "magnet" {
    // Do whatever you want.
}

@raymond-1227
Copy link

I tried the method, but I'm not sure why if I use the code, it'll say WebPageProxy::didFailProvisionalLoadForFrame: frameID=575, domain=NSURLErrorDomain, code=-999 when the code was set like this:

if components?.scheme == "roblox-player" {
      decisionHandler(.allow)
}

I think the error was dedicated to the custom scheme, because if I use webview.uiDelegate (which doesn't handle external links) the error doesn't appear.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment