I have a WkWebView where I load my webpage. The webpage is a questionnaire so there are several steps with questions and on final page I get the result. I want to detect when user is at the final page. The web page uses postMessage to send data. To get this change I have implemented webview with WKUserContentController like following:
private lazy var webView: WKWebView = {
let config = WKWebViewConfiguration()
let source = """
window.addEventListener('message', function(e) {
window.webkit.messageHandlers.message.postMessage(JSON.stringify(e.data));
});
"""
let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
// let script = WKUserScript(source: "alert('Hello, World!');", injectionTime: .atDocumentEnd, forMainFrameOnly: false)
config.userContentController.addUserScript(script)
config.userContentController.add(self, name: "message")
webView = WKWebView(frame: .zero, configuration: config)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
webView.navigationDelegate = self
return webView
}()
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message)
print(message.name)
guard let dict = message.body as? [String : AnyObject] else {
return
}
print(dict)
}
WKUserContentController, didReceive message is called on load of the web page but it is not called after subsequent url changes