I have added WKWebView to view via code in my class which extends UIViewController class, I am able to call JS function from iOS storyboard buttons successfully.
However, I want JS to be able to tell Swift when an ajax post request is complete... Luckily I found this page...
http://www.kinderas.com/technology/2014/6/15/wkwebview-and-javascript-in-ios-8-using-swift
var contentController = WKUserContentController()
contentController.addScriptMessageHandler(
self,
name: "callbackHandler"
)
var config = WKWebViewConfiguration()
config.userContentController = contentController
self.webView = WKWebView(
frame: self.containerView.bounds,
configuration: config
)
Here... I want to be able add script message handler after the webview is added to view.
Is it possible to call addScriptMessageHandler() after webview is already added to the view?
Yes, and it's really simple too:
let contentController = self.webView.configuration.userContentController
contentController.addScriptMessageHandler(self, name: "callbackHandler2")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With