Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 884
shramee Avatar asked Dec 04 '22 00:12

shramee


1 Answers

Yes, and it's really simple too:

let contentController = self.webView.configuration.userContentController
contentController.addScriptMessageHandler(self, name: "callbackHandler2")
like image 157
Code Different Avatar answered Dec 10 '22 13:12

Code Different