SlideShare a Scribd company logo
1 of 28
Download to read offline
Hybrid Apps and Qortoba:
Your own mini-Cordova
Ayman Mahfouz
VP of Engineering @ Webalo
December 2016
Agenda
- Bio
- Problem Context
- Introducing Hybrid Apps
- Native-to-JS communication
- Project Qortoba
- Q&A
Problem Context - Webalo Platform
www.webalo.com
Native Apps
Pros
● Performance
● Security
● Familiarity
● Access to Device
Cons
● Portability
● Maintenance
● Time to Market
So?
Native Apps - Shared Code
Shared Java code allows for extensibility, but how to open the Webalo
Client up for third party extension?
Solution - Hybrid App
Java /
Obj-C
WebView
HTML + JS
?
The Matrix!
Native to JavaScript
Android
Java to JavaScript
API
void evaluateJavascript(String script, ValueCallback<String> resultCallback)
webView.evaluateJavascript(“someJavaScriptFunction();”, new ValueCallback<String>() {
public void onReceiveValue(String s) {
JsonReader reader = new JsonReader(new StringReader(s));
JsonToken token = JsonReader.peek()
...
}
});
Usage
Java to JavaScript - Notes
Requirements
1. API level 19.
2. WebSettings.setJavaScriptEnabled(true) // false by default
3. Must be called on UI thread.
evaluateJavascript(...)
Properties
1. Asynchronous evaluation.
2. Context of currently displayed page.
3. Callback made on UI thread.
4. Callback value is a JSON object. To pass String values use
JsonReader.setLenient(true).
Java to JavaScript - Pre 19
void loadUrl(String url)
Usage
webView.loadUrl(“javascript:someJsFunction();”);
API
Pitfall - Navigate away
webView.loadUrl(“javascript:someJsFunction();void(0);”);
No return value!
[INFO:CONSOLE(1)] "Uncaught SyntaxError: Unexpected token ILLEGAL", source: (1)
Common error
Native to JavaScript
iOS
Objective-C to JavaScript
WKWebView API (iOS 8+)
- (void)evaluateJavaScript : (NSString *)javaScriptString
completionHandler : (void (^)(id, NSError *error))completionHandler;
[webView evaluateJavaScript : script completionHandler:^(id result, NSError *error) {
if (error == nil) {
if (result != nil) {
NSString* resultString = [NSString stringWithFormat:@"%@", result];
...
}
} else {
NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
}
}];
Usage
Objective-C to JavaScript - Pre iOS 8
UIWebView API
- (NSString *)stringByEvaluatingJavaScriptFromString : (NSString *)script;
NSString *title
= [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
NSString *ten
= [webView stringByEvaluatingJavaScriptFromString:@"var x = 2; x * 5;"];
Usage
Objective-C to JavaScript - Notes
- (void) viewDidLoad {
// Send page load request to Web View
}
- (void) webViewDidFinishLoad : (UIWebView *)webView {
// Ask Web View to evaluate JavaScript
}
Back to the Matrix!
JavaScript to Native
Android
JavaScript to Java
Inject objects into the displayed page context:
private final class Api {
public void showMessage(String message) {
Log.d(TAG, message);
}
}
webView.addJavascriptInterface(new Api(), "MyJavaObj");
Starting API 17
void addJavascriptInterface(Object serviceApi, String name)
Usage
API
MyJavaObj.showMessage(“Hello There!”);
JavaJS
@JavascriptInterface
JavaScript to Java - Notes
1. Injected objects will not appear in JavaScript until the page is next (re)loaded.
webView.loadData("", "text/html", null);
2. WebView interacts with Java object on a background thread.
3. Serialization of arguments
a. Simple types and strings
b. Serialize objects as JSON
4. Use WebChromeClient to handle callbacks
webView.setWebChromeClient(new WebChromeClient() {
public boolean onJsAlert(...) {
// display alert in OS theme
}
});
}
Troubleshooting
Use Chrome “Inspect” feature
chrome://inspect
Must enable debugging
WebView.setWebContentsDebuggingEnabled(true);
android.view.ViewRootImpl$CalledFromWrongThreadException
[INFO:CONSOLE(13)] "Uncaught ReferenceError: MyJavaObj is not defined"
1. Run calls from JavaScript on UI Thread.
2. Invoked too early
a. Wait till page loads WebViewClient.onPageFinished()
b. May need call to force page load using
webView.loadData("", "text/html", null);
Debugging
Common Causes
Common Errors
JavaScript to Native
iOS
JavaScript to Objective-C
Inject an object into WK
@interface MyHandler : NSObject<WKScriptMessageHandler> { … }
- (void)userContentController : (WKUserContentController *)userContentController
didReceiveScriptMessage: (WKScriptMessage *)message {
NSDictionary *dict = (NSDictionary*)message.body;
NSString *str = [dict objectForKey:@"strField"];
NSNumber *num = [dict objectForKey:@"numField"];
...
}
[webView.configuration.userContentController
addScriptMessageHandler : myHandlerObject
name : @"handlerNameInJs"];
Usage
API
window.webkit.messageHandlers.handlerNameInJs.postMessage
( { ‘strField’ : “Some string value”, ‘numField’ : 3 } );
Objective-CJS
JavaScript to Objective-C - Pre iOS 8
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest : (NSURLRequest *)request
navigationType : (UIWebViewNavigationType)navigationType {
NSURL* url = request.URL;
if ( ! [url.scheme isEqualToString:@"myapp"]) {
return YES;
}
// decode the invocation
NSString* methodName = [hostStrEncoded stringByRemovingPercentEncoding];
NSString* queryStr = [[url query] stringByRemovingPercentEncoding];
...
return NO;
}
Usage - UIWebViewDelegate
Point the browser to the function you want to invoke!
API
document.location.href = “myapp://methodName?param1=test&param2=3
Objective-CJS
The Matrix Reloaded!
Project Qortoba
Cordova (Qortoba) - Spain
Features
● Utilities for JavaScript-to-Native communications.
● Unified OS-version-independent interface.
● Strongly-typed Java interfaces proxying JavaScript.
● Hide UIWebView delegate implementation.
● Scripts for generating JavaScript classes.
● Communication with AngularJS services.
Project Qortoba
github.com/amahfouz/qortoba
Extensions
● Callbacks for JavaScript-to-Native.
● Handling object graphs.
● Object parameter serialization.
● More code generation scripts.
● Better error handling.
● Platforms other than Android and iOS.
Project Qortoba
github.com/amahfouz/qortoba
amahfouz@gmail.com
linkedin.com/in/amahfouz
github.com/amahfouz
Questions
amahfouz.github.io
slideshare.net/AymanMahfouz

More Related Content

What's hot

AngularJS intro
AngularJS introAngularJS intro
AngularJS introdizabl
 
Fly High With Angular - How to build an app using Angular
Fly High With Angular - How to build an app using AngularFly High With Angular - How to build an app using Angular
Fly High With Angular - How to build an app using AngularVacation Labs
 
Angularjs practical project experiences with javascript development in a bank
Angularjs practical project experiences with javascript development in a bankAngularjs practical project experiences with javascript development in a bank
Angularjs practical project experiences with javascript development in a bankDavid Amend
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish MinutesDan Wahlin
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Dan Wahlin
 
jQuery and AJAX with Rails
jQuery and AJAX with RailsjQuery and AJAX with Rails
jQuery and AJAX with RailsAlan Hecht
 
Transakcyjność w django
Transakcyjność w djangoTransakcyjność w django
Transakcyjność w djangoMarcin Baran
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overviewAlex Bachuk
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with ReduxVedran Blaženka
 

What's hot (20)

AngularJS intro
AngularJS introAngularJS intro
AngularJS intro
 
Fly High With Angular - How to build an app using Angular
Fly High With Angular - How to build an app using AngularFly High With Angular - How to build an app using Angular
Fly High With Angular - How to build an app using Angular
 
Angularjs practical project experiences with javascript development in a bank
Angularjs practical project experiences with javascript development in a bankAngularjs practical project experiences with javascript development in a bank
Angularjs practical project experiences with javascript development in a bank
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish Minutes
 
Getting Started With ReactJS
Getting Started With ReactJSGetting Started With ReactJS
Getting Started With ReactJS
 
Dive into AngularJS and directives
Dive into AngularJS and directivesDive into AngularJS and directives
Dive into AngularJS and directives
 
Angular js PPT
Angular js PPTAngular js PPT
Angular js PPT
 
Grails 101
Grails 101Grails 101
Grails 101
 
Angular js
Angular jsAngular js
Angular js
 
React & redux
React & reduxReact & redux
React & redux
 
Angular js - the beginning
Angular js - the beginningAngular js - the beginning
Angular js - the beginning
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
 
Java script
Java scriptJava script
Java script
 
jQuery and AJAX with Rails
jQuery and AJAX with RailsjQuery and AJAX with Rails
jQuery and AJAX with Rails
 
Android development
Android developmentAndroid development
Android development
 
Transakcyjność w django
Transakcyjność w djangoTransakcyjność w django
Transakcyjność w django
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 

Viewers also liked

Self-service Enterprise Mobility
Self-service Enterprise MobilitySelf-service Enterprise Mobility
Self-service Enterprise MobilityAyman Mahfouz
 
Working Abroad: Bridging the Culture Gap
Working Abroad: Bridging the Culture GapWorking Abroad: Bridging the Culture Gap
Working Abroad: Bridging the Culture GapAyman Mahfouz
 
Bazillion New Technologies
Bazillion New TechnologiesBazillion New Technologies
Bazillion New TechnologiesAyman Mahfouz
 
Hybrid apps: Java conversing with JavaScript
Hybrid apps: Java  conversing with  JavaScriptHybrid apps: Java  conversing with  JavaScript
Hybrid apps: Java conversing with JavaScriptAyman Mahfouz
 
Economia solidária como formas alternativas de economia
Economia solidária como formas alternativas de economiaEconomia solidária como formas alternativas de economia
Economia solidária como formas alternativas de economiaUniversity of Coimbra
 
Cameron Nangia-HIV/AIDS
Cameron Nangia-HIV/AIDSCameron Nangia-HIV/AIDS
Cameron Nangia-HIV/AIDScjnangia
 
Aids Awareness , Nss , Healthcare !
Aids Awareness , Nss , Healthcare !Aids Awareness , Nss , Healthcare !
Aids Awareness , Nss , Healthcare !Pradhan Rishi Sharma
 
Tulos foorumi 13042016_fingrid_jukka_ruusunen
Tulos foorumi 13042016_fingrid_jukka_ruusunenTulos foorumi 13042016_fingrid_jukka_ruusunen
Tulos foorumi 13042016_fingrid_jukka_ruusunenPROimpact_Oy
 
How “associate-first” learning drives more sales and satisfaction
How “associate-first” learning drives more sales and satisfactionHow “associate-first” learning drives more sales and satisfaction
How “associate-first” learning drives more sales and satisfactionAxonify
 
Monthly safety report 2012 10_october
Monthly safety report 2012 10_octoberMonthly safety report 2012 10_october
Monthly safety report 2012 10_octoberChinaHarbour
 

Viewers also liked (14)

Self-service Enterprise Mobility
Self-service Enterprise MobilitySelf-service Enterprise Mobility
Self-service Enterprise Mobility
 
Working Abroad: Bridging the Culture Gap
Working Abroad: Bridging the Culture GapWorking Abroad: Bridging the Culture Gap
Working Abroad: Bridging the Culture Gap
 
Bazillion New Technologies
Bazillion New TechnologiesBazillion New Technologies
Bazillion New Technologies
 
Hybrid apps: Java conversing with JavaScript
Hybrid apps: Java  conversing with  JavaScriptHybrid apps: Java  conversing with  JavaScript
Hybrid apps: Java conversing with JavaScript
 
Projeto Riscos
Projeto Riscos Projeto Riscos
Projeto Riscos
 
Chris oyakhilome photos
Chris oyakhilome photos Chris oyakhilome photos
Chris oyakhilome photos
 
Economia solidária como formas alternativas de economia
Economia solidária como formas alternativas de economiaEconomia solidária como formas alternativas de economia
Economia solidária como formas alternativas de economia
 
Cameron Nangia-HIV/AIDS
Cameron Nangia-HIV/AIDSCameron Nangia-HIV/AIDS
Cameron Nangia-HIV/AIDS
 
Aids Awareness , Nss , Healthcare !
Aids Awareness , Nss , Healthcare !Aids Awareness , Nss , Healthcare !
Aids Awareness , Nss , Healthcare !
 
Tulos foorumi 13042016_fingrid_jukka_ruusunen
Tulos foorumi 13042016_fingrid_jukka_ruusunenTulos foorumi 13042016_fingrid_jukka_ruusunen
Tulos foorumi 13042016_fingrid_jukka_ruusunen
 
Chris oyakhilome
Chris oyakhilomeChris oyakhilome
Chris oyakhilome
 
Friendship
FriendshipFriendship
Friendship
 
How “associate-first” learning drives more sales and satisfaction
How “associate-first” learning drives more sales and satisfactionHow “associate-first” learning drives more sales and satisfaction
How “associate-first” learning drives more sales and satisfaction
 
Monthly safety report 2012 10_october
Monthly safety report 2012 10_octoberMonthly safety report 2012 10_october
Monthly safety report 2012 10_october
 

Similar to Gdg dev fest hybrid apps your own mini-cordova

125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용NAVER D2
 
Hybrid App using WordPress
Hybrid App using WordPressHybrid App using WordPress
Hybrid App using WordPressHaim Michael
 
Custom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for AndroidCustom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for Androidmhant
 
The WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsThe WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsHaim Michael
 
The art of Building Bridges for Android Hybrid Apps
The art of Building Bridges for Android Hybrid AppsThe art of Building Bridges for Android Hybrid Apps
The art of Building Bridges for Android Hybrid AppsBartłomiej Pisulak
 
EWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD MessagesEWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD MessagesRob Tweed
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CNjojule
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJSWei Ru
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
Cloud Application Blueprints with Apache Brooklyn by Alex Henevald
Cloud Application Blueprints with Apache Brooklyn by Alex HenevaldCloud Application Blueprints with Apache Brooklyn by Alex Henevald
Cloud Application Blueprints with Apache Brooklyn by Alex Henevaldbuildacloud
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationAndrew Rota
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
 
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...Matt Spradley
 
Building an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and FirebaseBuilding an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and FirebaseMarina Coelho
 

Similar to Gdg dev fest hybrid apps your own mini-cordova (20)

125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용
 
Hybrid App using WordPress
Hybrid App using WordPressHybrid App using WordPress
Hybrid App using WordPress
 
Custom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for AndroidCustom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for Android
 
React native by example by Vadim Ruban
React native by example by Vadim RubanReact native by example by Vadim Ruban
React native by example by Vadim Ruban
 
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter LehtoJavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
 
The WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsThe WebView Role in Hybrid Applications
The WebView Role in Hybrid Applications
 
The art of Building Bridges for Android Hybrid Apps
The art of Building Bridges for Android Hybrid AppsThe art of Building Bridges for Android Hybrid Apps
The art of Building Bridges for Android Hybrid Apps
 
EWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD MessagesEWD 3 Training Course Part 14: Using Ajax for QEWD Messages
EWD 3 Training Course Part 14: Using Ajax for QEWD Messages
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CN
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Cloud Application Blueprints with Apache Brooklyn by Alex Henevald
Cloud Application Blueprints with Apache Brooklyn by Alex HenevaldCloud Application Blueprints with Apache Brooklyn by Alex Henevald
Cloud Application Blueprints with Apache Brooklyn by Alex Henevald
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP Application
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Mlocjs buzdin
Mlocjs buzdinMlocjs buzdin
Mlocjs buzdin
 
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
 
UIWebView Tips
UIWebView TipsUIWebView Tips
UIWebView Tips
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
NodeJS
NodeJSNodeJS
NodeJS
 
Building an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and FirebaseBuilding an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and Firebase
 

Gdg dev fest hybrid apps your own mini-cordova

  • 1. Hybrid Apps and Qortoba: Your own mini-Cordova Ayman Mahfouz VP of Engineering @ Webalo December 2016
  • 2. Agenda - Bio - Problem Context - Introducing Hybrid Apps - Native-to-JS communication - Project Qortoba - Q&A
  • 3. Problem Context - Webalo Platform www.webalo.com
  • 4. Native Apps Pros ● Performance ● Security ● Familiarity ● Access to Device Cons ● Portability ● Maintenance ● Time to Market So?
  • 5. Native Apps - Shared Code Shared Java code allows for extensibility, but how to open the Webalo Client up for third party extension?
  • 6. Solution - Hybrid App Java / Obj-C WebView HTML + JS ?
  • 9. Java to JavaScript API void evaluateJavascript(String script, ValueCallback<String> resultCallback) webView.evaluateJavascript(“someJavaScriptFunction();”, new ValueCallback<String>() { public void onReceiveValue(String s) { JsonReader reader = new JsonReader(new StringReader(s)); JsonToken token = JsonReader.peek() ... } }); Usage
  • 10. Java to JavaScript - Notes Requirements 1. API level 19. 2. WebSettings.setJavaScriptEnabled(true) // false by default 3. Must be called on UI thread. evaluateJavascript(...) Properties 1. Asynchronous evaluation. 2. Context of currently displayed page. 3. Callback made on UI thread. 4. Callback value is a JSON object. To pass String values use JsonReader.setLenient(true).
  • 11. Java to JavaScript - Pre 19 void loadUrl(String url) Usage webView.loadUrl(“javascript:someJsFunction();”); API Pitfall - Navigate away webView.loadUrl(“javascript:someJsFunction();void(0);”); No return value! [INFO:CONSOLE(1)] "Uncaught SyntaxError: Unexpected token ILLEGAL", source: (1) Common error
  • 13. Objective-C to JavaScript WKWebView API (iOS 8+) - (void)evaluateJavaScript : (NSString *)javaScriptString completionHandler : (void (^)(id, NSError *error))completionHandler; [webView evaluateJavaScript : script completionHandler:^(id result, NSError *error) { if (error == nil) { if (result != nil) { NSString* resultString = [NSString stringWithFormat:@"%@", result]; ... } } else { NSLog(@"evaluateJavaScript error : %@", error.localizedDescription); } }]; Usage
  • 14. Objective-C to JavaScript - Pre iOS 8 UIWebView API - (NSString *)stringByEvaluatingJavaScriptFromString : (NSString *)script; NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"]; NSString *ten = [webView stringByEvaluatingJavaScriptFromString:@"var x = 2; x * 5;"]; Usage
  • 15. Objective-C to JavaScript - Notes - (void) viewDidLoad { // Send page load request to Web View } - (void) webViewDidFinishLoad : (UIWebView *)webView { // Ask Web View to evaluate JavaScript }
  • 16. Back to the Matrix!
  • 18. JavaScript to Java Inject objects into the displayed page context: private final class Api { public void showMessage(String message) { Log.d(TAG, message); } } webView.addJavascriptInterface(new Api(), "MyJavaObj"); Starting API 17 void addJavascriptInterface(Object serviceApi, String name) Usage API MyJavaObj.showMessage(“Hello There!”); JavaJS @JavascriptInterface
  • 19. JavaScript to Java - Notes 1. Injected objects will not appear in JavaScript until the page is next (re)loaded. webView.loadData("", "text/html", null); 2. WebView interacts with Java object on a background thread. 3. Serialization of arguments a. Simple types and strings b. Serialize objects as JSON 4. Use WebChromeClient to handle callbacks webView.setWebChromeClient(new WebChromeClient() { public boolean onJsAlert(...) { // display alert in OS theme } }); }
  • 20. Troubleshooting Use Chrome “Inspect” feature chrome://inspect Must enable debugging WebView.setWebContentsDebuggingEnabled(true); android.view.ViewRootImpl$CalledFromWrongThreadException [INFO:CONSOLE(13)] "Uncaught ReferenceError: MyJavaObj is not defined" 1. Run calls from JavaScript on UI Thread. 2. Invoked too early a. Wait till page loads WebViewClient.onPageFinished() b. May need call to force page load using webView.loadData("", "text/html", null); Debugging Common Causes Common Errors
  • 22. JavaScript to Objective-C Inject an object into WK @interface MyHandler : NSObject<WKScriptMessageHandler> { … } - (void)userContentController : (WKUserContentController *)userContentController didReceiveScriptMessage: (WKScriptMessage *)message { NSDictionary *dict = (NSDictionary*)message.body; NSString *str = [dict objectForKey:@"strField"]; NSNumber *num = [dict objectForKey:@"numField"]; ... } [webView.configuration.userContentController addScriptMessageHandler : myHandlerObject name : @"handlerNameInJs"]; Usage API window.webkit.messageHandlers.handlerNameInJs.postMessage ( { ‘strField’ : “Some string value”, ‘numField’ : 3 } ); Objective-CJS
  • 23. JavaScript to Objective-C - Pre iOS 8 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest : (NSURLRequest *)request navigationType : (UIWebViewNavigationType)navigationType { NSURL* url = request.URL; if ( ! [url.scheme isEqualToString:@"myapp"]) { return YES; } // decode the invocation NSString* methodName = [hostStrEncoded stringByRemovingPercentEncoding]; NSString* queryStr = [[url query] stringByRemovingPercentEncoding]; ... return NO; } Usage - UIWebViewDelegate Point the browser to the function you want to invoke! API document.location.href = “myapp://methodName?param1=test&param2=3 Objective-CJS
  • 26. Features ● Utilities for JavaScript-to-Native communications. ● Unified OS-version-independent interface. ● Strongly-typed Java interfaces proxying JavaScript. ● Hide UIWebView delegate implementation. ● Scripts for generating JavaScript classes. ● Communication with AngularJS services. Project Qortoba github.com/amahfouz/qortoba
  • 27. Extensions ● Callbacks for JavaScript-to-Native. ● Handling object graphs. ● Object parameter serialization. ● More code generation scripts. ● Better error handling. ● Platforms other than Android and iOS. Project Qortoba github.com/amahfouz/qortoba