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

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

Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
Soó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
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
FIWARE
 

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

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

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 

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