There is a click button on my webpage, but I am not getting the click button callback from the webview in userContentController. The javascript is already implemented on the web end.
I have tried to inject the javascript from iOS end it get worked.
override func viewDidLoad() {
super.viewDidLoad()
let preferences = WKPreferences()
let contentController = WKUserContentController()
preferences.javaScriptEnabled = true
let source: String = """
window.onload = function() {
document.addEventListener("click", function(evt) {
var tagClicked = document.elementFromPoint(evt.clientX, evt.clientY);
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.getAccessToken) {
window.webkit.messageHandlers.Android.postMessage(JSON.stringify({
properties: {
unique_key: "some_unique_key_value"
}
}));
}
});
}
"""
let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(script)
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
configuration.userContentController = contentController
configuration.userContentController.add(self, name: "Android")
let webAppInterface = WebAppInterface(viewController: self)
self.webView = WKWebView(frame: self.view.frame, configuration: configuration)
webView.allowsBackForwardNavigationGestures = true
self.webView.uiDelegate = self
self.webView.navigationDelegate = self
self.webView.scrollView.delegate = self
self.view = webView
}
But the javascript is already implemented on the web end. So, I was trying with this code.
override func viewDidLoad() {
super.viewDidLoad()
// Initialize WKPreferences and enable JavaScript
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
// Create a WKUserContentController
let contentController = WKUserContentController()
// Create a WKWebViewConfiguration and set its preferences and user content controller
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
configuration.userContentController = contentController
// Add the message handler to receive messages from the web end
let webAppInterface = WebAppInterface(viewController: self)
configuration.userContentController.add(webAppInterface, name: "Android")
// Initialize the WKWebView with the configuration
self.webView = WKWebView(frame: self.view.frame, configuration: configuration)
webView.allowsBackForwardNavigationGestures = true
self.webView.uiDelegate = self
self.webView.navigationDelegate = self
self.webView.scrollView.delegate = self
self.view = webView
}
I am getting callback whenever I am injecting the JS but I need the webend response without injecting it from my side.
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
}
I am not able to find the issue that what’s wrong I am doing in my implementation.