How to let javascript call native function in WebView on iOS?
You may think about using an open-source framework to bridge the native app with JavaScript.
In fact, it is not necessary as long as you know what Apple’s framework feature can provide for us.
It’s very simple to implement without using any heavy open-source framework.
Below show 4 solutions on how to create JavaScripts to call native app in WebView for iOS.
URL interception:
- must redirect or refresh the page, so as the app can catch the redirect URL in function shouldStartLoadWithRequest.
- Supports iOS version ranging from 2 to 12
- Supports UIWebView
- Framework: UIWebView
This solution is widely used in lots of open source frameworks and compatible with iOS and Android. Android also can use the same method.
On WebView, we can simply refresh the page by invoking the following JavaScript function
// Format: location.href=[customized app name]://[any parameters]
// <customized app name>: you can define any name
// <any parameters>: you can define any parameters passed to the app from JavaScript
location.href=myapp://userId=1234
Then the app will intercept and parse this GET request with URL:[any link]://[any parameters] in function shouldStartLoadWithRequest.
WKScriptMessageHandler:
- Without redirect a page, JS can call the native function directly
- Supports iOS 8+
- Supports WKWebView
- Framework: WebKit
On WebView, the page can directly call the native function by trigger a button or an event. The app can get and parse the event in WKScriptMessageHandler.
JavaScriptCore:
- Without redirect a page, JS can call the native function
- Supports iOS 7+
- Supports UIWebView, not support WKWebView
- Framework: JavaScriptCore
This solution is limited to UIWebView and is the same as WKWebView that can let the page directly call the native function by triggering a button or an event.
Method interception:
- Without redirect, but a user needs to interact with the page to show an alert popup and click the button
- Supports iOS 8+
- Supports WkWebView
- Framework: WebKit
Conclusion
In this post, we provide 4 solutions to allow JavaScript invoke native functions on iOS. Basically, it’s very simple and easy to implement without any open-source libraries. I hope this tutorial will be helpful for you.
You might be interested in