Communicate between Javascript & WKWebView
Send data from Javascript to iOS code
Configure a WKUserContentController
on the WKWebView
to receive data
class MessageHandlerLeakAvoider: NSObject, WKScriptMessageHandler {
weak var delegate: WKScriptMessageHandler?
init(delegate: WKScriptMessageHandler) {
self.delegate = delegate
super.init()
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
self.delegate?.userContentController(
userContentController, didReceive: message)
}
}
let contentController = webView.configuration.userContentController
contentController.add(MessageHandlerLeakAvoider(self), name: "messageHandler")
extension ArticleViewController: WKScriptMessageHandler{
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let dict = message.body as? [String : AnyObject] else {
return
}
print(dict)
}
}
Send the data from Javascript
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.messageHandler) {
window.webkit.messageHandlers.messageHandler.postMessage({
"message": ""
});
}
Send data from iOS to Javascript code
Execute Javascript code on the webview to pass data to the web context.
let script = "window.updateFromNative(" + eventValue + ")"
webView.evaluateJavaScript(script) { (result, error) in
if let error {
print(error)
}
}
Create a Javascript method updateFromNative
to receive the data passed
window.updateFromNative = function (nativeData) {
};
Implement Engagement Starter
Show a Engagement Starter inside the WebView content and link it with the SDK.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.webView.evaluateJavaScript(
"""
setTimeout(function() {
document.querySelector('.vf-conversation-starter_link').onclick = function() {
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.messageHandler) {
window.webkit.messageHandlers.messageHandler.postMessage({
"action": "ENGAGEMENT_STARTER_CLICKED"
});
}
};
}, 2000);
""")
}
extension ArticleViewController: WKScriptMessageHandler{
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let data = message.body as? [String : AnyObject] else {
return
}
if data["action"] as? String == "ENGAGEMENT_STARTER_CLICKED" {
let originY = scrollView.convert(CGPoint.zero, from: commentsContainerView).y
scrollView.setContentOffset(CGPoint(x: 0, y: originY), animated: true)
}
}
}
Updated 3 months ago