This is my function in android :
@JavascriptInterface
public boolean GetMobileVersion() {
return true;
}
This is Calling function in JavaScript :
$(window).load(function () {
IsCallByMobileApp = false;
try {
IsCallByMobileApp = app.GetMobileVersion();/*Is call by android app*/
} catch (e) {
IsCallByMobileApp = false;
}
}
In iOS I am try to achieve same approach using WKWebView
like this but it's not working:
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
if(message.name == callbackhandler) {
webView.evaluateJavaScript("GetMobileVersion();") { (true, error) in
guard error == nil else {
print("there was an error")
return
}
print(Bool(true))
}
}
}
Can anyone tell me How to send true
to Javascript function? Please give me answer in detail because I am new to iOS and Swift.
I have created a GitHub project for this. https://github.com/BKRApps/WKWebView-JS. check it out for more details.
Update the JavaScript:
function getMobileVersion(){
webkit.messageHandlers.VersionHandler.postMessage({})
}
function receivedMobileVersion(mobileVersion){
//here you will be getting the mobile version. Then execute the logic.
// i have added this only to cross check the version. you don't need to add this.
if(mobileVersion === true) {
webkit.messageHandlers.VerifyHandler.postMessage({version:mobileVersion})
}
}
getMobileVersion()
Add the below code to WKWebView Configuration:
configuration.userContentController.add(self, name: "VersionHandler")
// i have added this only to cross check the version. you don't need to add this.
configuration.userContentController.add(self, name: "VerifyHandler")
Update the WKScriptMessageHandler delegate:
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name {
case "VersionHandler":
let mobileVersion = true //write the version logic and send the true or false.
let sendMobileVersionScript = "receivedMobileVersion(\(mobileVersion))"
self.wkWebView?.evaluateJavaScript("\(sendMobileVersionScript)", completionHandler: { (any, error) in
print("hello")
})
case "VerifyHandler":
print(message.body) // i have added this only to cross check the version. you
default:
break;
}
}
for more info : http://igomobile.de/2017/03/06/wkwebview-return-a-value-from-native-code-to-javascript/
Not sure if with WKWebView is the same as webview but you could try with plaintext as following:
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
if(message.name == callbackhandler) {
webView.evaluateJavaScript("GetMobileVersion(true);") { (true, error) in
guard error == nil else {
print("there was an error")
return
}
print(Bool(true))
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With