SlideShare a Scribd company logo
Hybrid Apps:
Your own mini-Cordova
Ayman Mahfouz
VP of Engineering @ Webalo
November 2016
Agenda
- Problem
- Hybrid apps
- Android
- Java to JavaScript
- JavaScript to Java
- iOS
- Objective-C to JavaScript
- JavaScript to Objective-C
- Talking Angular
- Summary
Problem Context - Webalo Platform
Problem Context - Webalo App
Shared Java code allows for extensibility, but how to open the Webalo
Client up for third party extension?
Solution - Hybrid App
HTML +
JavaScript
Java / Obj-C
WebView
Android App
● Java / Objective-C: Proprietary code.
● JavaScript: Third-party code.
Android
Java to JavaScript
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
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!
Android
JavaScript to Java
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);
[INFO:CONSOLE(1)] "Uncaught SyntaxError: Unexpected token ILLEGAL", source: (1)
[INFO:CONSOLE(13)] "Uncaught ReferenceError: MyJavaObj is not defined"
android.view.ViewRootImpl$CalledFromWrongThreadException
1. Run calls from JavaScript on UI Thread.
2. Wait till page loads WebViewClient.onPageFinished()
3. Force page load using
webView.loadData("", "text/html", null);
Debugging
Common Causes
Common Errors
iOS
Objective-C to JavaScript
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
}
iOS
JavaScript to Objective-C
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 Angular bit
Angular to Native
Wrap an Angular service around the injected Object.
angular.module('MyModule').service('WrapperService', function() {
this.showMessage = function(message) {
MyInjectedObj.showMessage(message);
};
this.someOtherMethod = function() {
MyInjectedObj.someOtherMethod();
};
});
Java to Angular
// Get the element for the angular application
var app = angular.element('[ng-app]');
// Get the injector from the application
var injector = app.injector();
// Get the service to be called
var myService = injector.get("MyService");
// Invoke the service
myService.someFunction();
What is the entry point from plain JavaScript to Angular?
Appreciate what PhoneGap does for you!
Summary
● Hybrid Apps
● Conversing with the Web View
● Extensions
○ Other platforms
○ Callbacks to JavaScript
○ Code generation
amahfouz@gmail.com
linkedin.com/in/amahfouz
aymanmahfouz.blogspot.com
slideshare.net/AymanMahfouz
github.com/amahfouz
Questions

More Related Content

PDF
Gdg dev fest hybrid apps your own mini-cordova
PDF
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
PDF
Android development
PDF
Workshop 12: AngularJS Parte I
PDF
The art of Building Bridges for Android Hybrid Apps
PPTX
Developing ASP.NET Applications Using the Model View Controller Pattern
PDF
Dmytro Zaitsev Viper: make your mvp cleaner
PPTX
Practical AngularJS
Gdg dev fest hybrid apps your own mini-cordova
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Android development
Workshop 12: AngularJS Parte I
The art of Building Bridges for Android Hybrid Apps
Developing ASP.NET Applications Using the Model View Controller Pattern
Dmytro Zaitsev Viper: make your mvp cleaner
Practical AngularJS

What's hot (20)

PDF
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
PDF
ajax_pdf
PPTX
Angularjs Basics
PPTX
AngularJs
PDF
AngularJS Framework
PDF
React JS and Redux
PDF
VBA API for scriptDB primer
PDF
«От экспериментов с инфраструктурой до внедрения в продакшен»​
PPTX
Dependency injection - the right way
PDF
AngularJS Workshop
PDF
준비하세요 Angular js 2.0
PDF
Workshop 24: React Native Introduction
PPTX
Knockout.js
PDF
Workshop 27: Isomorphic web apps with ReactJS
PDF
Workshop 14: AngularJS Parte III
PDF
Architectures in the compose world
ODP
AngularJs Crash Course
PDF
AngularJS Basics with Example
PDF
[FEConf Korea 2017]Angular 컴포넌트 대화법
PPTX
Mobile App Development: Primi passi con NativeScript e Angular 2
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
ajax_pdf
Angularjs Basics
AngularJs
AngularJS Framework
React JS and Redux
VBA API for scriptDB primer
«От экспериментов с инфраструктурой до внедрения в продакшен»​
Dependency injection - the right way
AngularJS Workshop
준비하세요 Angular js 2.0
Workshop 24: React Native Introduction
Knockout.js
Workshop 27: Isomorphic web apps with ReactJS
Workshop 14: AngularJS Parte III
Architectures in the compose world
AngularJs Crash Course
AngularJS Basics with Example
[FEConf Korea 2017]Angular 컴포넌트 대화법
Mobile App Development: Primi passi con NativeScript e Angular 2
Ad

Similar to Hybrid apps - Your own mini Cordova (20)

PDF
Hybrid apps: Java conversing with JavaScript
PPTX
Custom HTML5-Native Bridge for Android
PDF
The WebView Role in Hybrid Applications
PDF
Hybrid App using WordPress
PPTX
React native by example by Vadim Ruban
PDF
React Native for multi-platform mobile applications
PPTX
NodeJS
PDF
Workshop 26: React Native - The Native Side
ODP
Javascript frameworks: Backbone.js
PDF
125 고성능 web view-deview 2013 발표 자료_공유용
PPT
echo-o & Android App Dev - BarCamp Saigon 1
PDF
handout-05b
PDF
handout-05b
PDF
droidQuery: The Android port of jQuery
PPTX
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
PPTX
RIA / SPA with ASP.NET
PDF
Google Web Toolkit
PDF
Vaadin 7 CN
PDF
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
PPTX
Developing your first application using FIWARE
Hybrid apps: Java conversing with JavaScript
Custom HTML5-Native Bridge for Android
The WebView Role in Hybrid Applications
Hybrid App using WordPress
React native by example by Vadim Ruban
React Native for multi-platform mobile applications
NodeJS
Workshop 26: React Native - The Native Side
Javascript frameworks: Backbone.js
125 고성능 web view-deview 2013 발표 자료_공유용
echo-o & Android App Dev - BarCamp Saigon 1
handout-05b
handout-05b
droidQuery: The Android port of jQuery
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
RIA / SPA with ASP.NET
Google Web Toolkit
Vaadin 7 CN
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Developing your first application using FIWARE
Ad

More from Ayman Mahfouz (7)

PDF
Integrating Gmail with issue tracking 2018
PPTX
Modern Programming Languages - An overview
PPTX
Gdg dev fest 2107 to kotlin, with love
PPTX
Career Day - Software Engineer
ODP
Bazillion New Technologies
PDF
Self-service Enterprise Mobility
PPTX
Working Abroad: Bridging the Culture Gap
Integrating Gmail with issue tracking 2018
Modern Programming Languages - An overview
Gdg dev fest 2107 to kotlin, with love
Career Day - Software Engineer
Bazillion New Technologies
Self-service Enterprise Mobility
Working Abroad: Bridging the Culture Gap

Recently uploaded (20)

PPTX
Computer Software and OS of computer science of grade 11.pptx
PPTX
Advanced SystemCare Ultimate Crack + Portable (2025)
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
history of c programming in notes for students .pptx
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Complete Guide to Website Development in Malaysia for SMEs
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
Nekopoi APK 2025 free lastest update
PDF
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
Computer Software and OS of computer science of grade 11.pptx
Advanced SystemCare Ultimate Crack + Portable (2025)
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Reimagine Home Health with the Power of Agentic AI​
history of c programming in notes for students .pptx
Wondershare Filmora 15 Crack With Activation Key [2025
iTop VPN Free 5.6.0.5262 Crack latest version 2025
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Digital Systems & Binary Numbers (comprehensive )
Internet Downloader Manager (IDM) Crack 6.42 Build 41
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
CHAPTER 2 - PM Management and IT Context
Design an Analysis of Algorithms II-SECS-1021-03
Complete Guide to Website Development in Malaysia for SMEs
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Nekopoi APK 2025 free lastest update
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
wealthsignaloriginal-com-DS-text-... (1).pdf
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf

Hybrid apps - Your own mini Cordova

  • 1. Hybrid Apps: Your own mini-Cordova Ayman Mahfouz VP of Engineering @ Webalo November 2016
  • 2. Agenda - Problem - Hybrid apps - Android - Java to JavaScript - JavaScript to Java - iOS - Objective-C to JavaScript - JavaScript to Objective-C - Talking Angular - Summary
  • 3. Problem Context - Webalo Platform
  • 4. Problem Context - Webalo App Shared Java code allows for extensibility, but how to open the Webalo Client up for third party extension?
  • 5. Solution - Hybrid App HTML + JavaScript Java / Obj-C WebView Android App ● Java / Objective-C: Proprietary code. ● JavaScript: Third-party code.
  • 7. 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
  • 8. Java to JavaScript 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).
  • 9. 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!
  • 11. 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
  • 12. 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 } }); }
  • 13. Troubleshooting Use Chrome “Inspect” feature chrome://inspect Must enable debugging WebView.setWebContentsDebuggingEnabled(true); [INFO:CONSOLE(1)] "Uncaught SyntaxError: Unexpected token ILLEGAL", source: (1) [INFO:CONSOLE(13)] "Uncaught ReferenceError: MyJavaObj is not defined" android.view.ViewRootImpl$CalledFromWrongThreadException 1. Run calls from JavaScript on UI Thread. 2. Wait till page loads WebViewClient.onPageFinished() 3. Force page load using webView.loadData("", "text/html", null); Debugging Common Causes Common Errors
  • 15. 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
  • 16. 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
  • 17. Objective-C to JavaScript - Notes - (void) viewDidLoad { // Send page load request to Web View } - (void) webViewDidFinishLoad : (UIWebView *)webView { // Ask Web View to evaluate JavaScript }
  • 19. 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
  • 20. 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
  • 22. Angular to Native Wrap an Angular service around the injected Object. angular.module('MyModule').service('WrapperService', function() { this.showMessage = function(message) { MyInjectedObj.showMessage(message); }; this.someOtherMethod = function() { MyInjectedObj.someOtherMethod(); }; });
  • 23. Java to Angular // Get the element for the angular application var app = angular.element('[ng-app]'); // Get the injector from the application var injector = app.injector(); // Get the service to be called var myService = injector.get("MyService"); // Invoke the service myService.someFunction(); What is the entry point from plain JavaScript to Angular?
  • 24. Appreciate what PhoneGap does for you! Summary ● Hybrid Apps ● Conversing with the Web View ● Extensions ○ Other platforms ○ Callbacks to JavaScript ○ Code generation