Introduction to the

Have you ever been asked about Hybrid apps in your interview? I have to say that knowing Hybrid App was a plus in our front-end interview. Follow my steps today to get you through the Hybrid App and get you ready to respond to interviewers’ questions even if you haven’t done it yet.

In front of the author has introduced the mobile terminal H5 web development essential knowledge and mobile terminal H5 web development FAQ summary two articles, interested students can take a look. Today’s article mainly introduces Hybrid App and how the H5 page communicates with the App.

The types of APP

What is a Hybrid App? Don’t worry, next let the author introduce one by one.

Currently, apps are mainly divided into three categories, including Web App, Hybrid App and Native App.

Web App

A Web App is a website on a mobile terminal. The page is deployed on a server and accessed by users using major browsers. It is not an independent App and cannot be installed or published. Mobile Taobao is one of the most common Web apps.

Advantages:

  1. Low development cost, cross-platform, easy debugging.
  2. Low maintenance cost Updates do not need to notify users, do not need to manually upgrade, do not need to install apps, and do not occupy mobile phone memory.

Disadvantages:

  1. Unable to get system-level notifications, reminders, action effects, etc.
  2. Retention is low, design is limited and many experiences are poor.

Native App

Native App is often referred to as the Native App, which is divided into Android development and IOS development. Android is based on the Java language and invokes the apis provided by Google. IOS is based on Objective C or Swift and invokes the apis provided by Apple.

Advantages:

  1. Directly rely on the operating system, the strongest interaction, the best performance.
  2. Most powerful, especially in the interaction with the system, almost all functions can be achieved.

disadvantages

  1. The development cost is high, and it cannot be cross-platform. Different platforms, Android and iOS, must be independently developed.
  2. High barriers, native people have some barriers to entry, compared to the majority of front-end people. Updates are slow, especially after launching the app store and waiting for the approval cycle. High maintenance costs.

Hybrid App

Next is the protagonist of today, Hybrid App. The main principle is to realize part of the content that needs to be dynamically changed through H5. The H5 page is loaded through the native web loading control WebView (Android) or WKWebView (iOS). In this way, the H5 part can be changed at any time without issuing a version, and dynamic needs can be met; Also, H5 code can be developed once and run on both Android and iOS platforms, which can reduce development costs. In other words, the more features H5 has, the less development costs will be. We call this h5+ native development mode Hybrid development, and the APP developed in the Hybrid mode is called Hybrid application or Hybrid APP.

You can simply understand it as a hybrid of Web App and Native App.

Advantages:

  1. Low development cost, cross-platform, convenient debugging, low maintenance cost, reusable functions.
  2. The function is more perfect, the performance and experience is much better than web app, and the update is more free.

Disadvantages:

  1. Compared with native, performance still has a large loss, not suitable for interactive app.

conclusion

Do you have a certain understanding of the types of apps and Hybrid apps? Don’t the H5 pages we embed in the App need dynamic communication? Yes, it is. Next, let’s talk about how Hybrid App communicates with our H5 page.

App communicates with H5

Communication is divided into H5 end calling native App end method and native App end calling H5 end method. App is divided into IOS and Android, there are differences between them, we will introduce them separately below.

The App side calls the h5-side method

The App side calls the H5 side method, which must be bound to the window object.

Register the say method with the Window object.

window.say = (name) = > {
 alert(name)
}
Copy the code

Android calls the H5-side method

private void isAutoUser (a) {
    String username = mSpHelper.getAutoUser();
    
    if (TextUtils.isEmpty(username)) {
        return;
    }

    // 1.Android: loadUrl (Android 4.4- supported)
    // The drawback of this method is that it cannot get the return value of the function;
    // the say method is mounted on the window object by H5.
    mWebView.loadUrl("javascript:say('" + username + "')")

    EvaluateJavascript (Android 4.4+ support)
    EvaluateJavascript is highlighted here, and is currently the dominant method.
    // This method can get the function return value in the callback method;
    // the say method is mounted on the window object by H5.
    mWebView.evaluateJavascript("javascript:say('" + username + "')".new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String s) {
          // This is the result returned by js}});// The following two types of communication are not used much, so I will not focus on them here.
    
    // 3.Android: loadUrl (Android 4.4- supported)
    // Open a web link directly and pass parameters. This can also pass parameters to H5
    // mWebView.loadUrl("file:///android_asset/shop.html? name=" + username);
    
    // 4. Android can also use onJsAlert, onJsConfirm, onJsPrompt methods to intercept js call warning box, input box, and confirmation box.
}
Copy the code

IOS invokes methods on H5

IOS uses different languages with different invocation methods.

// Objective-C
// the say method is mounted on the window object by H5
[self.webView evaluateJavaScript:@"say('params')" completionHandler:nil];

// Swift
// the say method is mounted on the window object by H5
webview.stringByEvaluatingJavaScriptFromString("say('params')")
Copy the code

The H5 side calls the app-side method

Android and IOS have respective mount methods for H5 calls. The corresponding ones are: Apple UIWebview JavaScriptCore injection (not introduced here), Android addJavascriptInterface injection, Apple WKWebView scriptMessageHandler injection.

H5 calls the method on the Android side

Android addJavascriptInterface injection.

// The object name androidJSBridge can be changed at will.
addJavascriptInterface(new MyJaveScriptInterface(mContext), "androidJSBridge");

// MyJaveScriptInterface class
@JavascriptInterface
public aliPay (String payJson) {
  aliPayHelper.pay(payJson);
  // Android calls methods exposed to H5 can return values directly.
  return 'success';
}
Copy the code

H5 calls the method exposed on the Android side.

// androidJSBridge here is based on the name registered above.
// Javascript calls to Android Native methods must pass basic types of data, not reference types. If you want to pass reference types, you need to use json.stringify ().
const result = window.androidJSBridge.aliPay('the string parameters');
console.log(result);
Copy the code

H5 Invokes the IOS method

Apple WKWebView scriptMessageHandler injection

#pragmaMark-oc registers the method register method for JS calls
- (void)addScriptFunction {
    self.wkUserContentController = [self.webView configuration].userContentController;

    [self.wkUserContentController addScriptMessageHandler:self name:@"register"];
}

#pragmaThe Mark-register method
- (void)register:(id)body {
     NSDictionary *dict = body;
    [self.userDefaults setObject:[dict objectForKey:@"password"] forKey:[dict objectForKey:@"username"]]. The result cannot be returned directly. You need to call the method on H5 again to tell H5 that the registration is successful. [self.webView evaluateJavaScript:@"registerCallback(true)" completionHandler:nil];
}
Copy the code

The ios method exposed to web calls cannot have a return value directly. If a return value is required, you need to call the Web method to pass the return value. (That is, two steps).

H5 invokes the method exposed on IOS.

// Unlike Android, the Webkit. messageHandlers in ios are fixed and cannot be changed.
// Do not pass parameters
window.webkit.messageHandlers.register.postMessage(null);
// Pass parameters
// Unlike Android, ios parameters can be basic types and reference data types.
window.webkit.messageHandlers.register.postMessage(params);
Copy the code

Two-way communication between Android and IOS

  1. The H5 end calls the Android end methodWindow.androidjsbridge. Method name (parameter)Here,androidJSBridgeThe name is not fixed and can be customized. The fixed formula for H5 terminal to call the method on IOS terminal iswindow.webkit.messageHandlers. Method name.postMessage (parameter).
  2. The parameter passed by the H5 side when calling the Android side method can only be the basic data type. If the reference data type needs to be passed, it needs to be usedJSON.stringfy()To deal with. On the IOS side, both basic and reference data types can be passed.
  3. H5 can directly return values when calling Android methods. The IOS server cannot directly return a value.

Unified handling

So, again, the question is, how do we distinguish between the H5 side where we call Android and IOS methods in different ways? Don’t worry. I have a recipe for this.

/** * Determine the phone system type *@returns phoneSys* /
function phoneSystem() {
  var u = navigator.userAgent.toLowerCase();
  let phoneSys = ' '
  if (/android|linux/.test(u)) {// Android phone
    phoneSys = 'android'
  } else if (/iphone|ipad|ipod/.test(u)) {// iPhone
    phoneSys = 'ios'
  } else if (u.indexOf('windows Phone') > -1) {/ / winphone mobile phones
    phoneSys = 'other'
  }
  return phoneSys
}

/ / call
// The type of the argument and the return value of the method need to be handled.
function call(message) {
  let phoneSys = phoneSystem()
  if (typeof window.webkit ! ="undefined" && phoneSys == 'ios') {
    window.webkit.messageHandlers.call.postMessage(message);
  } else if (typeofjimiJS ! = ="undefined" && phoneSys == 'android') {
    window.jimiJS.call(message); }}Copy the code

Afterword.

This article is the author’s personal study notes, if there are fallacies, please inform, thank you! If this article helped you, please give it a thumbs up