Skip to content

    Frontend System Design

    WebView and Hybrid App Architecture

    Design a hybrid app as a web view inside a native shell: the JavaScript bridge, navigation and origin rules, lifecycle and state, and where sign-in belongs.

    By Published 13 min read

    • frontend-system-design
    • webview
    • hybrid-apps
    • capacitor
    • javascript-bridge
    Share

    Standard lessonintermediateFrontend System Design

    Before this: Mobile and Cross-Platform Front Ends

    What you'll learn: By the end of this lesson you will be able to describe a hybrid app as a web view hosted by a native shell, design the JavaScript bridge between the two as a small versioned message protocol, decide which pages may reach the bridge, keep navigation and the back gesture under control, survive rotation and process death, and explain why sign-in should leave the web view.

    Think of a picture frame. The picture is your web app and the frame is the native shell. The frame decides how the picture hangs, what happens when someone knocks it, and who may touch the glass. A hybrid app is that arrangement: a browser component embedded in a native app, with a narrow, designed opening between them.

    This lesson builds on mobile and cross-platform front ends, which compares the five ways to put a front end on a phone; here we go deep on one. The running example is the shopper app of the ShopStream grocery marketplace: a product page, a cart and a checkout that already exist as a website, plus a barcode scanner for reorders. The later lessons on choosing between mobile web, hybrid and native, and on React Native architecture are named in plain text only.

    Verified on 2026-12-02 against the Android developer documentation, the Capacitor documentation and RFC 8252. No mobile device or emulator was available. The two Node scripts on this page were run; every Kotlin and TypeScript snippet that touches a platform was not run.

    The core idea

    A hybrid app has three parts, and each has a different owner.

    1. The web content: HTML, CSS and JavaScript that the web team ships. It can come from files packaged in the app or from a server.
    2. The web view: a browser engine component that the operating system provides and the app embeds. Android's documentation says WebView "lets you display web pages as a part of your activity layout" and does not include "the features of a fully developed web browser, such as navigation controls or an address bar".
    3. The native shell and the bridge: the app around the web view, and the channel through which the page asks it for things the web cannot do, such as a scanner or secure storage.

    The architecture of a hybrid app is mostly the design of the third part. The page and the shell update on different schedules (a deploy against a store release) and fail in different ways. Everything the page can ask the shell to do is an attack surface, and everything the shell does to the page, such as reloading it, is a lifecycle event the page must survive.

    Figure 1. The three parts of a hybrid app

    A hybrid app: web content, web view and native shellWeb content to Web view (renders in); Web view to Bridge (messages); Bridge to Native shell; Native shell to Phone OS (native calls); Web view to ShopStream API (HTTPS)Web content: your pagesWeb contentyour pagesWeb view: OS browser engineWeb viewOS browser engineBridge: message protocolBridgemessage protocolNative shell: pluginsNative shellpluginsPhone OS: camera, storage, pushPhone OScamera, storage,pushShopStream APIShopStream APIrenders inmessagesnative callsHTTPS

    How to read this: the two accent boxes are the architecture. The page reaches the shell only through the bridge, while ordinary data still goes to the API over HTTPS like any web page.

    What the shell gives you, and what it costs

    Capacitor describes itself as "a cross-platform native runtime" that creates "Web Native apps", with "a Plugin API for Swift on iOS, Java on Android, and JavaScript for the web". A plugin has one TypeScript interface and an implementation per platform: its documentation shows a shared interface, a web implementation, and says that methods added to the interface must be implemented on every platform you support. That last point is the cost. Each plugin is native code you maintain. Capacitor's web helpers getPlatform() and isNativePlatform() let the page ask where it runs, and a plugin-availability check lets a fallback take over.

    Android notes a cost for the web view itself: it says WebView "runs on a Chromium-based engine with separate processes and native code, its baseline memory usage is higher than standard Android views", and instances retain memory after the view leaves the layout unless you remove the WebView from its parent and call destroy().

    The bridge is a protocol

    There are three generations of Android API for the page to call the shell. The documentation compares them:

    Mechanism Style Origin control Documentation's advice
    addWebMessageListener Asynchronous messages, bidirectional Allowlist of origin rules Recommended
    postWebMessage Asynchronous, main frame only A target origin on send An alternative for older versions
    addJavascriptInterface Synchronous method calls None: exposed to every frame, including iframes Legacy

    The legacy mechanism is the dangerous one. Android's warning says that addJavascriptInterface "lets JavaScript control your Android app" and that if the HTML in the web view is untrustworthy, "an attacker can include HTML that executes your client-side code". Its advice is to use it only when you wrote all the HTML and JavaScript shown, and not to let users navigate within the web view to pages that are not yours.

    addWebMessageListener adds an origin allowlist. The documentation says rules are matched against scheme, host and port, paths are ignored, and a wildcard is only allowed at the start of the host: https://*.example.com matches https://foo.example.com but not https://example.com. The listener's callback runs on the main thread, so heavy work must be moved off it, and the API carries strings or byte arrays, so structured data is serialized by you. The page must call addWebMessageListener before navigating, so that the object exists from the start of the page load.

    Whichever you use, treat the bridge as a versioned message protocol, not a pile of functions.

    Figure 2. One bridge call, end to end

    sequenceDiagram accTitle: A bridge call from the page to the native shell and back accDescr: The page sends a versioned JSON request with an id. The shell checks the origin, the protocol version and the method allowlist, runs the native work with a timeout, and sends back a reply carrying the same id with either a result or an error code. The page matches the reply to the pending request by id. participant P as Page (web view) participant B as Bridge participant N as Native plugin P->>B: request {v, id, method, params} B->>B: check origin, version, allowlist B->>N: run method with a timeout N-->>B: result or failure B-->>P: reply {id, result or error code} P->>P: match reply to pending id

    How to read this: every request carries an id so the page can have several in flight and match each reply. The checks happen on the native side, because the page is the part that may be untrustworthy.

    Illustration 1: the minimal example, origin rules

    The documented origin-rule semantics are small enough to model. This script is a teaching model of the rules described above, not the platform's code. Run in Node:

    function parseOrigin(o) {
      const u = new URL(o);
      return { scheme: u.protocol.slice(0, -1), host: u.hostname, port: u.port || (u.protocol === "https:" ? "443" : "80") };
    }
    function allowed(rules, sourceOrigin) {
      const s = parseOrigin(sourceOrigin);
      return rules.some((rule) => {
        const wildcard = rule.includes("://*.");
        const r = parseOrigin(rule.replace("://*.", "://"));
        if (r.scheme !== s.scheme || r.port !== s.port) return false;
        return wildcard ? s.host.endsWith("." + r.host) : s.host === r.host;
      });
    }
    const rules = ["https://shop.example.com", "https://*.example.org"];
    const tests = [
      "https://shop.example.com/cart",
      "https://shop.example.com:8443/cart",
      "http://shop.example.com/cart",
      "https://evil.example.net",
      "https://a.example.org",
      "https://example.org",
    ];
    for (const t of tests) console.log(t.padEnd(38), allowed(rules, t));

    Output, from running it in Node 26.13.1:

    https://shop.example.com/cart          true
    https://shop.example.com:8443/cart     false
    http://shop.example.com/cart           false
    https://evil.example.net               false
    https://a.example.org                  true
    https://example.org                    false

    The path never matters, the port and scheme do, and a bare domain is not covered by its own subdomain wildcard. On a real device the check is made by the platform before the page can see the bridge object at all.

    On Android, the registration looks like this (adapted from the documentation, not run):

    val listener = WebViewCompat.WebMessageListener { _, message, sourceOrigin, _, replyProxy ->
        // Parse message.data, check the method, then reply on a worker thread.
        replyProxy.postMessage("ack")
    }
    if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
        WebViewCompat.addWebMessageListener(
            webView, "shopBridge", setOf("https://app.shopstream.example"), listener
        )
    }

    The documentation says to check WebViewFeature.isFeatureSupported() first, because these APIs belong to the Jetpack Webkit library and the web view version on a device may not support them. Origin rules do not protect against cross-site scripting inside your own trusted origin; the documentation advises validating message payloads before sensitive native operations. See cross-site scripting defenses and Content Security Policy.

    By default, Android says, tapping a link in a web view launches an app that handles URLs, usually the default browser. Setting a WebViewClient makes links load inside the web view, and overriding shouldOverrideUrlLoading gives you control: return false for URLs the web view should load itself and handle the rest (launch an intent, for example). The documentation shows a host check against your own domain, warns against calling loadUrl inside that method, and says malformed URLs are handled inconsistently, so use a custom scheme or an HTTPS URL on a domain you control.

    Windows are a second door. New-window requests are ignored by default; to keep it that way for target="_blank" links, the documentation's safest recipe is setSupportMultipleWindows(true) without overriding onCreateWindow.

    Figure 3. Deciding what a tapped link does

    flowchart TD accTitle: Deciding what happens when a link is tapped in the web view accDescr: A tapped link is checked. A link on the app's own origin loads in the web view. A custom app scheme link is handled by the shell as an action. Any other link opens in the system browser, and the web view never navigates to a foreign page. L["Link tapped"] --> Q1{"Own origin?"} Q1 -->|yes| A["Load in the web view"] Q1 -->|no| Q2{"App scheme link?"} Q2 -->|yes| B["Shell handles it as an action"] Q2 -->|no| C["Open in the system browser"]

    How to read this: the bridge only exists for pages in the first branch. A web view that follows foreign links is a web view whose bridge a stranger's page might call, which is why the allowlist and the navigation rule belong together.

    Back is the other half. canGoBack() and goBack() let the app walk the web view's history before leaving the screen. If the page is a single-page app with its own router, decide who owns back: the router (the shell forwards back through the bridge) or the web view history, not both.

    Lifecycle: the shell can reload or end the page

    Android's documentation says configuration changes such as rotation or dismissing the keyboard "cause a WebView object's activity to be destroyed and a new activity to be created, which also creates a new WebView object that loads the destroyed object's URL". saveState and restoreState keep the navigation context. Their documentation adds a trap: the saved-state budget is 1 MB shared across the process, exceeding it raises TransactionTooLargeException, and wiping the history to avoid that destroys back navigation. It recommends WebViewCompat.saveState() with a maxSizeBytes limit, which drops the oldest entries from the saved copy only, and includeForwardState set to false when the app has no forward button.

    Saved web view state is navigation context, not application data. The page must persist its own state (a half-filled form, a cart) as the user works. See state persistence and synchronization and offline-first sync.

    Illustration 2: the realistic example, a versioned bridge

    The shopper app needs the scanner, a share sheet and device information. The native side of the bridge is a dispatcher that parses a versioned envelope, rejects unknown methods, and answers every request with the same id and either a result or a code. This Node script models that dispatcher; the handlers are fakes. Run in Node:

    const SHELL_BRIDGE_VERSION = 2;
    const handlers = {
      "device.info": async () => ({ platform: "android", shellBridge: SHELL_BRIDGE_VERSION }),
      "scanner.scan": async () => ({ code: "5901234123457" }),
      "share.text": async ({ text }) => (typeof text === "string" ? { shared: true } : Promise.reject(new Error("text must be a string"))),
      "slow.call": () => new Promise(() => {}), // never answers
    };
    async function handle(raw, timeoutMs = 20) {
      let msg;
      try { msg = JSON.parse(raw); } catch { return { id: null, error: { code: "bad_json" } }; }
      if (msg.v > SHELL_BRIDGE_VERSION) return { id: msg.id, error: { code: "update_required", have: SHELL_BRIDGE_VERSION } };
      const fn = Object.hasOwn(handlers, msg.method) ? handlers[msg.method] : null;
      if (!fn) return { id: msg.id, error: { code: "unknown_method" } };
      const timeout = new Promise((_, rej) => setTimeout(() => rej(new Error("timeout")), timeoutMs));
      try {
        return { id: msg.id, result: await Promise.race([fn(msg.params ?? {}), timeout]) };
      } catch (e) {
        return { id: msg.id, error: { code: e.message === "timeout" ? "timeout" : "failed", message: e.message } };
      }
    }
    const calls = [
      { v: 1, id: 1, method: "device.info" },
      { v: 1, id: 2, method: "scanner.scan" },
      { v: 1, id: 3, method: "share.text", params: { text: 42 } },
      { v: 1, id: 4, method: "toString" },
      { v: 3, id: 5, method: "device.info" },
      { v: 1, id: 6, method: "slow.call" },
    ];
    for (const c of calls) console.log(JSON.stringify(await handle(JSON.stringify(c))));
    console.log(JSON.stringify(await handle("{nope")));

    Output, from running it in Node 26.13.1:

    {"id":1,"result":{"platform":"android","shellBridge":2}}
    {"id":2,"result":{"code":"5901234123457"}}
    {"id":3,"error":{"code":"failed","message":"text must be a string"}}
    {"id":4,"error":{"code":"unknown_method"}}
    {"id":5,"error":{"code":"update_required","have":2}}
    {"id":6,"error":{"code":"timeout","message":"timeout"}}
    {"id":null,"error":{"code":"bad_json"}}

    A method not on the allowlist (toString) is refused, because the lookup uses Object.hasOwn and not a plain property read. A page newer than the shell gets update_required. A call that never answers ends in a timeout, and a malformed message gets an error and not a crash. Data that is large or binary should not travel as JSON strings: the Android documentation says Base64 adds roughly 33% overhead, recommends byte arrays through WebMessageCompat, and says very large files (over 10 MB) are better streamed through shouldInterceptRequest.

    Where sign-in belongs

    A web view is the tempting place to show a login page, and the standards say not to. RFC 8252, the best current practice for OAuth in native apps, says "native apps MUST use an external user-agent to perform OAuth authorization requests" and that they "MUST NOT use embedded user-agents". Its reasons: the host app can access the user's full credential, for example by recording keystrokes or copying cookies, and an embedded view does not share authentication state with the browser, so users sign in again for each app. Android's documentation adds that the system browser does not share its application data with your app. Open the system browser and return to the app through a redirect. See authentication flows end to end for the flow.

    Illustration 3: a failure, the rotation that erased a form

    A shopper types an address into the checkout form inside the web view, rotates the phone to see the map, and the form is empty. By the documentation, rotation destroyed the activity and the new WebView reloaded the URL. The navigation was restored if the shell called saveState, but the page was reloaded from the network and in-memory form values were gone. Two fixes at different layers: the shell saves and restores state, and the page writes the form to local storage as the user types (see cookies and web storage), which also survives process death.

    Trade-offs

    Decision Gain Cost Wrong when
    Hybrid instead of mobile web Store presence, device plugins A native shell and plugins to maintain The web platform already offers every feature you need
    Packaged web assets Opens without a network, fixed bridge origin Updates wait for a store release You must ship fixes within hours
    Remote web content Deploy like a website Needs a network; every page is a bridge caller You cannot trust or pin the origin
    Bridge as a message protocol Versioning, timeouts, allowlist More code than direct calls There are only one or two trivial calls
    Sign-in in the system browser Credentials stay out of your app, shared sign-in A redirect round trip An identity provider you do not control

    Capacitor's documentation says its server.url option, which loads an external URL in the web view, "is not intended for use in production", and the same note applies to allowNavigation.

    Build it

    This lesson has no lab. The two Node scripts above are teaching models with no repository folder and no golden file, and the Kotlin snippet was not run because no device or emulator was available.

    In practice: the ShopStream shopper app as a hybrid

    This is a realistic scenario, not a case history. It is a composite built from common patterns, and every number is an illustrative assumption.

    The situation

    ShopStream has a web team of six (illustrative) and a checkout that already works well on the web. Shoppers ask for an icon, a barcode scanner for reorders, and push alerts. There is budget for one app team, not three.

    Starting architecture

    Starting architecture: web onlyWebsite to ShopStream API (HTTPS); ShopStream API to Backend servicesWebsite: mobile browserWebsitemobile browserShopStream APIShopStream APIBackend servicesBackendservicesHTTPS

    Options considered

    Option Gain Cost Wrong when
    A. Mobile web only No store, one codebase No scanner or store listing Store presence is a goal
    B. Packaged web app in a hybrid shell Reuses the checkout, adds plugins Bridge, web view lifecycle and store releases The UI must feel fully native
    C. Native apps Best platform fit Two more codebases One team and one budget

    The decision

    Option B, with two rules. The web view loads only packaged assets from the app's own origin and has one bridge with an origin allowlist, a version field and a method allowlist as in Illustration 2. Sign-in opens the system browser. This is one defensible answer for this team, not a rule.

    Rollout and verification

    Ship the shell with the scanner and share plugins to a small staged store release first. Verify on real devices, which this lesson could not do: rotation, back at the first screen, long backgrounding, airplane mode, and a bridge message from a non-allowlisted origin (it must fail).

    The 2 a.m. failure

    After a web release, scanner calls from older app versions return unknown_method and shoppers cannot reorder.

    First checks: which app versions send which method names; whether the release changed a bridge method or its parameters. Mitigation: make the page check device.info for the shell's bridge version at startup and fall back to manual entry when the scanner method is missing; return update_required instead of failing silently. Follow-up: treat the bridge protocol like a public API with a deprecation window, because old shells stay in the field until users update.

    Architect's notes

    • Name the bridge surface in a list. If you cannot list every method the page can call, you cannot review it.
    • Prefer messages over injected objects.
    • Own the version field. Page and shell ship separately, so skew is normal.
    • Persist from the page. A web view's saved state is not your data.
    • Test on devices. The checks in this lesson cannot replace them.

    Common mistakes

    • Exposing a broad native object to every page and frame.
    • Treating the origin allowlist as complete XSS protection.
    • Following foreign links inside the web view.
    • Wiping navigation history to dodge the saved-state limit.
    • Showing a sign-in page in an embedded web view.
    • Calling web view methods from a bridge thread instead of the UI thread.

    Key takeaways

    • A hybrid app is web content in a web view inside a native shell; the architecture is mostly the bridge between them.
    • Use origin-checked asynchronous messages, with a version, an id, an allowlist and timeouts.
    • Control navigation: own-origin pages load in the view, everything else leaves.
    • The shell can reload or end the page; save state in both layers and size it.
    • Sign in with the system browser, as RFC 8252 requires for OAuth in native apps.

    Practice exercises

    Exercise 1 (30 min). Add a scanner.cancel method to the Illustration 2 script and a test row that sends it twice. Which error code should the second call get, and why?

    Exercise 2 (1 hour). List every bridge method a ShopStream page would need and mark each as read-only, changes state, or sensitive. Which ones need payload validation even from a trusted origin?

    Exercise 3 (half day). Write the bridge protocol as a one-page spec: envelope, error codes and deprecation policy.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments