4

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?

0

2 Answers 2

16

Yes, and it's really simple too:

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

Answering my own question ;P

Though @CodeDifferent's answer works a treat :D

But we can make it even simpler by doing this...

self.webView.configuration.userContentController.addScriptMessageHandler(
    self,
    name: "callbackHandler"
)

or more compact...

self.webView.configuration.userContentController.addScriptMessageHandler(self,name: "callbackHandler")

This is what I used, works like a charm :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.