Common Patterns for H5 and Native App Interaction
This article explains common H5‑to‑native app interaction patterns, detailing basic interfaces, one‑way and two‑way calls, implementation approaches, and the considerations for whether the H5 or the native side leads the integration, with code examples for Android and iOS.
In China the term “H5” is used to describe HTML5 pages that run inside a mobile application's WebView. The WebView (UIWebView/WKWebView on iOS, WebView on Android) provides a container where JavaScript can call native objects and native code can invoke JavaScript functions, enabling data exchange between the two environments.
The basic bridge consists of two objects: NativeBridge (injected by the native app) and JSBridge (exposed by the H5 page). Each object offers a single method – NativeBridge.callNative(action, params, whoCare) for JavaScript‑to‑native calls and JSBridge.callJS(action, params, whoAmI) for native‑to‑JavaScript calls. The action string identifies the operation, params carries a JSON payload, and the numeric flags indicate which side initiates or cares about the response.
One‑way calls from JavaScript to the app include actions such as loadUrl (open a new URL) and loadContent (navigate to a native screen). Example for Android: NativeBridge.addJavascriptInterface(new JsObject(), "injectedObject"); webView.loadUrl("javascript:alert(injectedObject.toString())"); On the reverse direction the app can query JavaScript with can_back to decide whether a back navigation needs user confirmation, returning a JSON like {"can":true,"target":"prev"} .
Two‑way calls combine a request from JavaScript and a callback from the native side. Typical actions are loadComponent (show a native UI component) and displayNextButton (control a top‑right button). After the user selects a value, the native code calls back with set_location or save_form to deliver the result to JavaScript. Sample callback: JSBridge.callJS({action:'set_location',params:{value:'Beijing Chaoyang'},whoAmI:1});
The article also discusses which side should dominate the integration. An H5‑centric approach keeps most business logic in the WebView, allowing rapid updates without repackaging the native app, while a native‑centric approach embeds logic in the app, which can lead to version‑control challenges. The choice depends on project constraints and team preferences.
Overall, the guide provides a practical reference for implementing H5‑App communication, covering interface definitions, code examples for Android and iOS, and strategic considerations for hybrid mobile development.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.