I am developing an ios application that uses WKWebview to display my web application. I have a simple button in my frontend which send the message to WKWebview via window.webkit.messageHandlers.isLocationPresent.postMessage("checkLocation")
.
IOS Swift
In my viewDidLoad
let configuration = WKWebViewConfiguration()
let controller = WKUserContentController()
// name of handler called from js code
controller.add(self,name: "isLocationPresent")
configuration.userContentController = controller
let webView = WKWebView(frame: self.view.frame,configuration:configuration)
On ios side I have implemented the userContentController via
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "isLocationPresent" {
// my logic for checking if location service is available
// if location is present the method returns true else false
let isGpsAvailable:Bool = self.checkLocationServiceState()
if isGpsAvailable {
webView.evaluateJavaScript("sendComment(\(isGpsAvailable ))", completionHandler: {(result,error) in
print(result)
print(error)
})
}
else{
// perform other logic there
}
}
}
Javascript
document.getElementById('click').onclick = function() {
window.webkit.messageHandlers.isLocationPresent.postMessage("checkLocation").
}
function sendComment(aval) {
if(aval) {
makeRequest()
}
else {
// logic to handle if false
}
}
But everytime i click the button, the evaluateJavascript always throws Javascript Reference error : variable sendComment not found.
The web app is dynamic, each html element is created by javascript.
I have three views, when user clicks on a list, he goes to second view, where click
button is rendered.
So, calling webview when page loads will not work, because the button element is not rendered in my first view
sendComment() function should only be called by ios when , button is clicked on frontend. I have other use cases also, where the function call should take place in ios when user performs the action in frontend only.