AlexEdunov
AlexEdunov

Reputation: 357

Share session between multiple WKWebView

I need to implement billing logic. It does a few redirects and then opens the new frame in the new window – that's how it works on the web-browser.

I'm showing the billing frame in the WKWebView. I catch the moment when it wants to open the new frame (navigationAction.targetFrame.isNil) and ask webView to load new request. New frame is loading, but some redirects aren't happening and billing shows me an error. Looks like the session is lost.

I tried another way: load new request in the new webView. When I initialize the webView I pass the processPull from the previous one, following this article: https://github.com/ShingoFukuyama/WKWebViewTips#cookie-sharing-between-multiple-wkwebviews Problem wasn't solve.

lazy var webView: WKWebView = { [unowned self] in
    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    preferences.javaScriptCanOpenWindowsAutomatically = true

    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences

    let webView = WKWebView(frame: CGRect.zero, configuration: configuration)
    webView.navigationDelegate = self
    webView.UIDelegate = self
    webView.estimatedProgress
    webView.scrollView.backgroundColor = UIColor.binomoDarkGrey()
    self.view.addSubview(webView)
    webView.snp_makeConstraints { [unowned self] (make) in
        make.edges.equalTo(self.view)
    }

    return webView
}()

// MARK: WKNavigationDelegate

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    if navigationAction.targetFrame.isNil {
        decisionHandler(.Cancel)
        webView.loadRequest(navigationAction.request)
    } else {
        decisionHandler(.Allow)
    }
}

Upvotes: 1

Views: 2627

Answers (1)

AlexEdunov
AlexEdunov

Reputation: 357

I've solved the problem pretty tricky by setting target attribure from JavaScript.

extension WebKitViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        let js = "document.getElementsByTagName('form')[0].setAttribute('target', '_self')"
        webView.evaluateJavaScript(js, completionHandler: nil)
    }
}

Upvotes: 1

Related Questions