Andrey Chernukha Andrey Chernukha - 1 year ago 401
Swift Question

WKWebView. didStartProvisionalNavigation not called

I'm using

in my app and everything works fine until user is going to For the main page of this site everything is fine as well but when user leaves the main page and goes for example to or any other page on this site the delegate methods
not called. But I need these methods in order to detect the start of a navigation.
is called at the very beginning however it is called multiple times and I feel that using this method is not a perfect solution. So my question is: what can I do in such a situation? What so especial can be at that site what doesn't make
call its delegate methods and what may be a reliable solution in this case? Thanks

Answer Source

I do not know very well web development, but it seems to me that the problem with JavaScript of the site. It seems that the transitions between the site pages and their loading is carried out with help of JavaScript. That JavaScript conflict with native WKWebView handlers.

But! You can inject your own JavaScript with handler at the beginning of the page. And when the page begins to open, the script will work first.

Full example code

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {

    var webView = WKWebView()
    let scriptName = "GetUrl"

    override func viewDidLoad() {

        let contentController = WKUserContentController();
        let script = "webkit.messageHandlers.\(scriptName).postMessage(document.URL)"
        let userScript = WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true)
        contentController.add(self, name: scriptName)

        let config = WKWebViewConfiguration()
        config.userContentController = contentController

        webView = WKWebView(frame:  UIScreen.main.bounds, configuration: config)
        webView.navigationDelegate = self

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if == scriptName {
            if let url = message.body as? String {
                if url.contains("") {
                    print("!!! \(url)")

    override func viewDidAppear(_ animated: Bool) {
        loadUrl(string: "")

    func loadUrl(string: String) {
        if let url = URL(string: string) {
            webView.load(URLRequest(url: url))


add in your Info.plist transport security setting



enter image description here


enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download