Search code examples
iosswiftwkwebview

Disable Youtube app redirect from WKWebview in swift


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

Solution

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