Catch Javascript Event in iOS WKWebview with Swift
Based on the answer from @Alex Pelletier, which really helped me, here is the solution the my question.
In my "loadView()" function, here is what I have :
let contentController = WKUserContentController();
contentController.addScriptMessageHandler(
self,
name: "callbackHandler"
)
let config = WKWebViewConfiguration()
config.userContentController = contentController
webView = WKWebView(frame: CGRectZero, configuration: config)
webView.navigationDelegate = self
view = webView
My function to handle the Javascript event which is sent to Swift :
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
{
if(message.name == "callbackHandler") {
print("Launch my Native Camera")
}
}
... And finally, my Javascript (jQuery) code when a click happens on my camera button (in HTML) :
$(document).ready(function() {
function callNativeApp () {
try {
webkit.messageHandlers.callbackHandler.postMessage("camera");
} catch(err) {
console.log('The native context does not exist yet');
}
}
$(".menu-camera-icon").click(function() {
callNativeApp();
});
});
I hope it will help someone else :-) !
First lets create a js file. In the js, when an element has been you clicked you can send a message back like so:
varmessageToPost = {'ButtonId':'clickMeButton'};
window.webkit.messageHandlers.buttonClicked.postMessage(messageToPost);
After you have created the js file and the wkwebview you need to inject the script:
// Setup WKUserContentController instance for injecting user script
var userController:WKUserContentController= WKUserContentController()
// Get script that's to be injected into the document
let js:String= GetScriptFromResources()
// Specify when and where and what user script needs to be injected into the web document
var userScript:WKUserScript = WKUserScript(source: js,
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd
forMainFrameOnly: false)
// Add the user script to the WKUserContentController instance
userController.addUserScript(userScript)
// Configure the WKWebViewConfiguration instance with the WKUserContentController
webCfg.userContentController= userController;
//set the message handler
userController.addScriptMessageHandler(self, name: "buttonClicked")
Finally you have to add listener function:
func userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage) {
if let messageBody:NSDictionary= message.body as? NSDictionary{
// Do stuff with messageBody
}
}
Source Code