Mobile Development 19 min read

Designing the Communication Layer and H5 Container for Hybrid Mobile Apps

This article explains how to design a hybrid app's communication layer using JSBridge, outlines native‑H5 interaction patterns, presents bridge protocol implementations, discusses UI responsibilities, and describes offline H5 container architecture with local URL routing and update mechanisms.

Art of Distributed System Architecture Design
Art of Distributed System Architecture Design
Art of Distributed System Architecture Design
Designing the Communication Layer and H5 Container for Hybrid Mobile Apps

Communication

As a cross‑language development model, the communication layer is the first thing to consider and design in a Hybrid architecture; all subsequent logic is built upon it.

Native (using Android as an example) and H5 communication, basic principle:

Android calls H5: use the WebView's loadUrl method to execute JavaScript directly, similar to typing JS in a browser address bar. webview.loadUrl("javascript: alert('hello world')");

H5 calls Android: the WebView can intercept any URL request initiated by H5; by agreeing on a URL scheme, the intercepted URL is processed (consumed) to achieve H5‑to‑Android calls. var ifm = document.createElement('iframe'); ifm.src = 'jsbridge://namespace.method?[...args]';

JSBridge is what we usually call the bridge protocol; the basic communication principle is simple, and the following sections detail its concrete implementation.

P.S.: Registering private protocols is common. For example, itunes:// launches the Apple Store, alipay:// launches Alipay, and tencent:// launches Tencent apps.

Bridge Protocol Implementation

Because JavaScript runs in a single thread, to avoid blocking the main thread and to guarantee ordered H5 calls, interfaces that need a result (GET‑type) adopt a JSONP‑like design.

Similar to HTTP request/response objects, the caller sends the API name, parameters, and a request signature to the callee; the callee processes the request and returns the result together with the signature, allowing the caller to locate the corresponding callback and complete the communication loop.

Illustrations of H5‑to‑Native and Native‑to‑H5 calls (Android example) are shown below.

Hybrid API Design Based on the Bridge Protocol

JSBridge, as a generic private protocol, is usually shared at the team or company level, so it should be decoupled from business logic. Its internal details are encapsulated, exposing platform‑level APIs to the upper layers.

The following is a stripped‑down implementation of the Hybrid API's JavaScript part (project address omitted).

// /lib/jsbridge/core.js
function assignAPI(name, callback) {
  var names = name.split(/\./);
  var ns = names.shift();
  var fnName = names.pop();
  var root = createNamespace(JSBridge[ns], names);
  if (fnName) root[fnName] = callback || function() {};
}

Adding an API:

// /lib/jsbridge/api.js
var assign = require('./core.js').assignAPI;
assign('util.compassImage', function(path, callback, quality, width, height) {
  JSBridge.invokeApp('os.getInfo', {
    path: path,
    quality: quality || 80,
    width: width || 'auto',
    height: height || 'auto',
    callback: callback
  });
});

H5 application calling the API:

// h5/music/index.js
JSBridge.util.compassImage('http://cdn.foo.com/images/bar.png', function(r) {
  console.log(r.value);
  // => base64 data
});

Interface and Interaction (Native vs. H5 Responsibility Division)

Both Native and H5 can render UI, but hybrid development must decide which parts belong to Native and which to H5.

The main reason for using a hybrid approach is to combine H5's cross‑platform rapid iteration with Native's smooth performance and system API access.

Generally, content should be presented with H5, while performance‑critical or hardware‑intensive tasks (animations, multithreading, IO) are handled by Native.

However, certain scenarios are better served by Native UI:

Key Screens and Highly Interactive Interfaces

Security‑sensitive screens such as registration, login, and payment are often implemented in Native to prevent malicious attacks and because their UI changes infrequently.

Complex animations and gesture handling on low‑end devices also favor Native implementation.

Example: a music playback screen with a wave‑style background that requires smooth left‑right sliding.

Navigation Component Implemented in Native

Navigation bars (back button, title, optional menu) are difficult to achieve with H5 pull‑down bounce effects, especially on weak networks where a white screen may appear.

Therefore, the navigation bar is usually a Native component combined with a WebView. The API JSBridge.layout.setHeader customizes a simple header:

// /h5/pages/index.js
JSBridge.layout.setHeader({
  background: { color: '#00FF00', opacity: 0.8 },
  buttons: [
    {
      icon: '../images/back.png',
      width: 16,
      height: 16,
      onClick: function() { JSBridge.back(); }
    },
    {
      text: 'Music Home',
      color: '#00FF00',
      fontSize: 14,
      left: 10
    }
  ]
});

Special cases such as tabbed pages with swipe gestures require custom WebView containers and dedicated APIs, e.g.:

// /h5/pages/index.js
JSBridge.view.openMusic({ 'tab': 'personal' });

When the tab content is an SPA, the URL might be /music.html#personal ; for multi‑page apps it could be /music-personal.html .

System‑Level UI Components Implemented in Native

Common UI components like alert and toast are better implemented in Native for consistency with the app’s style and to avoid sizing or coordinate errors.

JSBridge.ui.toast('Hello world!');

Default Screens Implemented in Native

Native can monitor H5 loading progress, display loading animations, and provide fallback screens for 404/5xx errors, preventing the app from appearing frozen.

Designing the H5 Container

The H5 container is the core of the hybrid architecture, responsible for fast, stable, and robust execution of H5 content.

H5 Offline Access

Hybrid development aims to mitigate slow web‑app access on poor networks by pre‑loading H5 resources onto the device, making them appear as fast as native pages.

Offline access is not just copying files to the SD card; it must handle versioning, fallback to online resources, and selective packaging.

Offline Dynamic Update Mechanism

Updating offline resources involves coordination among H5, Native, and the server. A long‑connection channel pushes new package information to the client, which then downloads, verifies, and merges the new bundle.

The update payload includes project name, version, update strategy (incremental or full), CDN URL, and MD5 checksum.

Local Url Router

The Native side intercepts static resource requests and maps them to local files. A mapping table (e.g., source-router.json ) generated by the H5 build process tells the container how to resolve URLs.

Example directory after unpacking:

$ cd h5 && tree .
├── js/
├── css/
├── img/
├── pages
│   ├── index.html
│   └── list.html
└── source-router.json

Sample source-router.json :

{
  "protocol": "http",
  "host": "o2o.xx.com",
  "localRoot": "[/storage/0/data/h5/o2o/]",
  "localFolder": "o2o.xx.com",
  "rules": {
    "/index.html": "pages/index.html",
    "/js/": "js/"
  }
}

When a request matches a local file, the container returns it directly; otherwise it falls back to an HTTP request, optionally downloading the resource for future offline use.

Data Channel

Reporting: Unified collection and reporting of user interaction data and navigation funnels by the H5 container.

Ajax Proxy: Wrap AJAX calls to bypass same‑origin restrictions and provide a more efficient communication channel for H5 data transfer.

Native Extensions for H5

Expose hardware capabilities (screen rotation, camera, microphone, location, etc.) to H5 through well‑defined interfaces.

Summary

The overall hybrid client architecture is illustrated below, highlighting the critical H5 container design, the long‑connection Synchronize Service for server pushes (including offline packages), and the Source Merge Service for updating local resources.

It is evident that the most complex and essential part of a hybrid app architecture is the design of the H5 container.

AndroidWebViewH5HybridBridgeofflineJSBridge
Art of Distributed System Architecture Design
Written by

Art of Distributed System Architecture Design

Introductions to large-scale distributed system architectures; insights and knowledge sharing on large-scale internet system architecture; front-end web architecture overviews; practical tips and experiences with PHP, JavaScript, Erlang, C/C++ and other languages in large-scale internet system development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.