Robert Hossein
Robert Hossein

Reputation: 43

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

Upvotes: 4

Views: 1465

Answers (2)

Jeff
Jeff

Reputation: 891

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

Upvotes: 4

Rajat Sharma
Rajat Sharma

Reputation: 32

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.

Upvotes: -1

Related Questions