I am using WKWebView, and it's working well, and I can now receive and process messages from loaded Javascript as long as it's called from withing the web code.
However I always get and error when I call webView!.evaluateJavaScript(source)
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={NSLocalizedDescription=A JavaScript exception occurred}
I have tried lots of ways to get this function called, but this is just where I stand at the moment.
My web view code:
let getLoggedInScript = "function getLoggedInUser(){return userJsonObject;}"
// in loadView()
let contentController = WKUserContentController();
let userScript = WKUserScript(
source: getLoggedInScript,
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
forMainFrameOnly: false
)
contentController.addUserScript(userScript)
contentController.addScriptMessageHandler(
self,
name: "wk_getLoggedInUserHandler"
)
contentController.addScriptMessageHandler(
self,
name: "wk_makePhoneCallHandler"
)
contentController.addScriptMessageHandler(
self,
name: "wk_pageDidLoadHandler"
)
let config = WKWebViewConfiguration()
config.userContentController = contentController
webView = WKWebView(frame: self.view.frame, configuration: config)
webView.navigationDelegate = self
view = webView
// in view class
func wk_getLoggedInUser(){
if loadingView {return}
let source = "if(wk_getLoggedInUser) wk_getLoggedInUser();"
self.webView!.evaluateJavaScript(source) { (result, error) -> Void in
if error != nil {
self.logger.log("JavaScript run error: \(error!)")
}
}
}
I can open WebInspector and goto the console and run the funtion and it reaches my IOS message handler, I am just returning the object at the moment, but have tried calling : webkit.messageHandlers.wk_getLoggedInUserHandler.postMessage(json); and this arrives in XCode....