Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView: how to disable Prevent cross-site tracking?

My app has 1 ViewController that loads a web app url that uses Auth0 to handle login. In iOS 13.3, the webView has since stopped working to load other pages after login.

However, when I tried using Safari on Mac, the webapp works if I disable Prevent cross-site tracking. How can I do this in WKWebView?

preferences

class MainViewController: UIViewController {

    private var webView: WKWebView!
    private var webViewConfiguration: WKWebViewConfiguration = {
        let source: String = "var meta = document.createElement('meta');" +
            "meta.name = 'viewport';" +
            "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';" +
            "var head = document.getElementsByTagName('head')[0];" + "head.appendChild(meta);";
        let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        let userContentController: WKUserContentController = WKUserContentController()
        let conf = WKWebViewConfiguration()
        conf.userContentController = userContentController
        userContentController.addUserScript(script)
        return conf
    }()

    override var prefersStatusBarHidden: Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
    }

    private func setupView() {
        webView = WKWebView(frame: self.view.frame, configuration: webViewConfiguration)
        webView.scrollView.delegate = self
        webView.navigationDelegate = self

        title = "My App"
        view.backgroundColor = UIColor.white
        view.addSubview(webView)
        view.addConstraintsWithFormat("H:|[v0]|", views: webView)
        view.addConstraintsWithFormat("V:|[v0]|", views: webView)

        // Adding deviceId and deviceName for analytics
        let endpointString = AppSettings.appUrl + "/?deviceId=\(deviceId)&deviceName=\(deviceName)"
        let escapedUrlString = endpointString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""

        if let url = URL(string: escapedUrlString) {
            Logger.log(message: "Loading with url - \(escapedUrlString)", event: .info)
            let request = URLRequest(url: url)
            webView.load(request)
        }
    }
}

extension MainViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        shouldShowNativeError = false
        if let url = webView.url?.absoluteString {
            Logger.log(message: "didFinish loading url: \(url)", event: .info)
        }
    }

    func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        if let serverTrust = challenge.protectionSpace.serverTrust {
            let exceptions = SecTrustCopyExceptions(serverTrust)
            SecTrustSetExceptions(serverTrust, exceptions)
            let credential = URLCredential(trust: serverTrust)
            completionHandler(.useCredential, credential)
        } else {
            completionHandler(.useCredential, nil)
        }
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url,
            let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
            let scheme = components.scheme {

            if scheme == "blob" {
                self.blobItemUrl = url
                navigationController?.setNavigationBarHidden(false, animated: true)
                navigationItem.leftBarButtonItem = backBarButtonItem
                navigationItem.rightBarButtonItem = shareBarButtonItem
            }
        }
        decisionHandler(.allow)
    }
}
like image 886
Vina Avatar asked Jan 01 '26 02:01

Vina


1 Answers

Try

self.webView.configuration.processPool.perform(Selector(("_setCookieAcceptPolicy:")), with: HTTPCookie.AcceptPolicy.always)

Put it in "setupView()", after "webView.navigationDelegate = self"

EDIT : Apparently, you can't use this if you want to publish your app in App Store


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!