I am working on an app that is using a WKWebView and I am trying to add an event listener when the user clicks on a button on the web page. The button as no id so I am working with the class.
I am able to set it up properly on chrome using the inspect console:
For my Swift development I have tried to add a function inside a WKWebView extension so it can be reused like that:
extension WKWebView {
/// Adds a event listener that will be call on WKScriptMessageHandler - didReceiveMessage
/// - Parameters:
/// - elementID: The name of the element
/// - callbackID: The ID for the callback
/// - elementType: The type of element to get
/// - completion: Callback triggered went script has been appended to WKWebView
//NOT WORKING
func addEventListener(id: String, callbackID: String, elementType: ElementType, handler: WKScriptMessageHandler, completion: ((Error?)->Void)?) {
let scriptString: String
switch elementType {
case .id:
scriptString = """
document.getElementById('\(id)').addEventListener('click', function(){
webkit.messageHandlers.refreshWebPage.postMessage("status":"ok");
});
"""
case .class:
scriptString = """
document.getElementsByClassName('\(id)')[0].addEventListener('click', function(){
webkit.messageHandlers.refreshWebPage.postMessage("status":"ok");
});
"""
}
let script = WKUserScript(source: scriptString, injectionTime: .atDocumentStart, forMainFrameOnly: false)
configuration.userContentController.addUserScript(script)
configuration.userContentController.add(handler, name: "postMessage")
}
}
Then, on the UIViewController, that contains the WKWebView:
//MARK: WKNavigationDelegate implementation
extension ArtpadWebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.addEventListener(id: "top_left_menu", callbackID: backCallbackID, elementType: .class, handler: self, completion: nil)
}
}
//MARK: WKScriptMessageHandler implementation
extension ArtpadWebViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("HO!")
}
}
However, the WKScriptMessageHandler function is not called... I have been trying to different solutions I found but non of them has worked. What am I missing?
Thank you