SlideShare a Scribd company logo
1 of 25
Download to read offline
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

What's hot

SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...Inhacking
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and ReduxGlib Kechyn
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 
«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​FDConf
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0Jeado Ko
 
Workshop 24: React Native Introduction
Workshop 24: React Native IntroductionWorkshop 24: React Native Introduction
Workshop 24: React Native IntroductionVisual Engineering
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSVisual Engineering
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
 
Architectures in the compose world
Architectures in the compose worldArchitectures in the compose world
Architectures in the compose worldFabio Collini
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법Jeado Ko
 
Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Filippo Matteo Riggio
 

What's hot (20)

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

Similar to Hybrid apps - Your own mini Cordova

Hybrid apps: Java conversing with JavaScript
Hybrid apps: Java  conversing with  JavaScriptHybrid apps: Java  conversing with  JavaScript
Hybrid apps: Java conversing with JavaScriptAyman Mahfouz
 
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
 
Hybrid App using WordPress
Hybrid App using WordPressHybrid App using WordPress
Hybrid App using WordPressHaim Michael
 
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
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsSoós Gábor
 
125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용NAVER D2
 
echo-o & Android App Dev - BarCamp Saigon 1
echo-o & Android App Dev - BarCamp Saigon 1echo-o & Android App Dev - BarCamp Saigon 1
echo-o & Android App Dev - BarCamp Saigon 1huyzing
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQueryPhDBrown
 
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
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CNjojule
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitIMC Institute
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWAREFIWARE
 

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

Hybrid apps: Java conversing with JavaScript
Hybrid apps: Java  conversing with  JavaScriptHybrid apps: Java  conversing with  JavaScript
Hybrid apps: Java conversing with JavaScript
 
Custom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for AndroidCustom HTML5-Native Bridge for Android
Custom HTML5-Native Bridge for Android
 
The WebView Role in Hybrid Applications
The WebView Role in Hybrid ApplicationsThe WebView Role in Hybrid Applications
The WebView Role in Hybrid Applications
 
Hybrid App using WordPress
Hybrid App using WordPressHybrid App using WordPress
Hybrid App using WordPress
 
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
 
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
 
NodeJS
NodeJSNodeJS
NodeJS
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
 
125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용
 
echo-o & Android App Dev - BarCamp Saigon 1
echo-o & Android App Dev - BarCamp Saigon 1echo-o & Android App Dev - BarCamp Saigon 1
echo-o & Android App Dev - BarCamp Saigon 1
 
handout-05b
handout-05bhandout-05b
handout-05b
 
handout-05b
handout-05bhandout-05b
handout-05b
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQuery
 
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...
 
RIA / SPA with ASP.NET
RIA / SPA with ASP.NETRIA / SPA with ASP.NET
RIA / SPA with ASP.NET
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CN
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 

More from Ayman Mahfouz

Integrating Gmail with issue tracking 2018
Integrating Gmail with issue tracking 2018Integrating Gmail with issue tracking 2018
Integrating Gmail with issue tracking 2018Ayman Mahfouz
 
Modern Programming Languages - An overview
Modern Programming Languages - An overviewModern Programming Languages - An overview
Modern Programming Languages - An overviewAyman Mahfouz
 
Gdg dev fest 2107 to kotlin, with love
Gdg dev fest 2107   to kotlin, with loveGdg dev fest 2107   to kotlin, with love
Gdg dev fest 2107 to kotlin, with loveAyman Mahfouz
 
Career Day - Software Engineer
Career Day - Software EngineerCareer Day - Software Engineer
Career Day - Software EngineerAyman Mahfouz
 
Bazillion New Technologies
Bazillion New TechnologiesBazillion New Technologies
Bazillion New TechnologiesAyman Mahfouz
 
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
 

More from Ayman Mahfouz (7)

Integrating Gmail with issue tracking 2018
Integrating Gmail with issue tracking 2018Integrating Gmail with issue tracking 2018
Integrating Gmail with issue tracking 2018
 
Modern Programming Languages - An overview
Modern Programming Languages - An overviewModern Programming Languages - An overview
Modern Programming Languages - An overview
 
Gdg dev fest 2107 to kotlin, with love
Gdg dev fest 2107   to kotlin, with loveGdg dev fest 2107   to kotlin, with love
Gdg dev fest 2107 to kotlin, with love
 
Career Day - Software Engineer
Career Day - Software EngineerCareer Day - Software Engineer
Career Day - Software Engineer
 
Bazillion New Technologies
Bazillion New TechnologiesBazillion New Technologies
Bazillion New Technologies
 
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
 

Recently uploaded

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 

Recently uploaded (20)

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.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