How to prevent WKWebView open instagram app automatically?

I have been struggling to prevent WkWebView open Instagram app automatically when a user clicked a hyperlink on WKWebView. Currently, my app is able to open the new window/new tab request from my web app and load into a new ViewController which creating another WKWebView to handle the request. However, whenever I clicked the link which is opening the user's Instagram profile, iPhone will automatically open the installed Instagram app. I have tried a few approaches and it is still not working as expected. I have another social media app which is Facebook and it is working as expected because it doesn't open the installed Facebook app on my phone and able to load into the new ViewController.

Scenario 1: Although able to open a new tab, but the entire webview has stopped working.

Scenario 2: Unlimited loop due to will always trigger the decidePolicyFor function.

Scenario 3: Delete installed Instagram app, It wouldn't open the app automatically and able to load into the local WkWebView but this is not the solution.

Thank you in advance and sorry if I didn't provide a clear description.

Code Block
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let host = navigationAction.request.url?.host {
if host == "www.instagram.com" {
/* Scenario 2, unlimited loop */
if let url = navigationAction.request.url {
let request = URLRequest(url: url)
self.webView.load(request)
}
/* Scenario 1, prevent loading user's instagram profile in local wkwebview */
decisionHandler(.cancel)
return
}
}
decisionHandler(.allow)
}


Replies

What does not work with decidePolicyForNavigationAction ?

The function itself doesn't have any error, I am just showing an approach that I tried last time and yet still not working as expected. It is still automatically redirect me to installed Instagram app on my phone.

try loading the response outside the browser first (URLSessionTask / Data w/ URL init) and loading that into the browser with its proper URL.