Shramee Srivastav Shramee Srivastav - 5 months ago 78
Swift Question

Call addScriptMessageHandler after adding WKWebView to view

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?

Answer

Yes, and it's really simple too:

let contentController = self.webView.configuration.userContentController
contentController.addScriptMessageHandler(self, name: "callbackHandler2")