Disable Youtube app redirect from WKWebview in swift

Viewed 785

I developed simple web browser with WKWebView in Swift. When I click Youtube link, Youtube app is auto launched. I hope to play Youtube video inside my web browser. I don't need to launch Youtube app. Please help me.

Here are my sample code.

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    let webViewConfiguration = WKWebViewConfiguration()
    webViewConfiguration.allowsInlineMediaPlayback = true
    wkWebView.configuration.allowsInlineMediaPlayback = true
    wkWebView.navigationDelegate = self
    let myURL = URL(string: "https://www.google.com")
    let youtubeRequest = URLRequest(url: myURL!)
    wkWebView.load(youtubeRequest)
}
2 Answers

Yes, you can do this.

First you need to set up a WKNavigationDelegate in your webview, then in webview:decidePolicyFor method cancel any link activated youtube requests, and force it to load within your webview.

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.navigationType == .linkActivated && navigationAction.request.url?.host?.hasSuffix("youtube.com") {
        decisionHandler(.cancel)
        DispatchQueue.main.async {
            webView.load(navigationAction.request)
        }
    } else {
        decisionHandler(.allow)
    }
}

Unfortunately you can't do that programatically. Following are the steps to achieve something like you want manually.

  1. Open youtube app from Home screen
  2. Tap on your profile picture on the upper right corner.
  3. Go to Settings and tap on Google app Settings
  4. Check the Safari Option.
Related