@yandeu/js-bridge 0.0.3 on npm

A bridge from your web page to the phone

A JS bridge passes messages between a web page and the native app around it. @yandeu/js-bridge is the bridge for Flutter WebView apps. Your page calls WebView.statusBar.setColor(), and the app does the work.

In a normal browser the bridge loads, but async native calls return an error result.

One call, one answer request answer
  1. Web page calls a method
  2. Bridge @yandeu/js-bridge
  3. Flutter app runs the action

The app runs the action on the device, then sends the answer back to the page.

01 What a bridge does

Messages out, answers back

The page and the app exchange JSON strings. A request names an action. If the page needs an answer, the request also carries a callbackId, and the app replies with the same id. The bridge then resolves the matching promise.

  1. 1

    Your page calls a method

    await WebView.statusBar.setColor('#000000')

  2. 2

    The bridge posts JSON

    It sends the message to the app through the WebViewCommunication channel.

  3. 3

    The app acts, then replies

    The app sends a reply with window.postMessage, using the same callbackId.

  4. 4

    The promise resolves

    Your await returns { ok: true, payload } or { ok: false, errorMessage }.

messages (simplified)
// Fire and forget. No answer comes back, so callbackId is empty.
WebViewCommunication.postMessage('{"action":"core_fullscreen_enter","callbackId":""}')

// Async. The reply from the app carries the same callbackId.
WebViewCommunication.postMessage('{"action":"core_status-bar_set-color","payload":{"color":"#000000"},"callbackId":"k3j9x2ab"}')

// Reply from the app, delivered as a window message:
{ "ok": true, "payload": {}, "callbackId": "k3j9x2ab" }

How the bridge detects the app

The bridge checks the user agent for the word WebView. Inside the app, it connects on load and WebView.isReady becomes true. In a normal browser, isReady stays false, and async calls return { ok: false, errorMessage: 'Not running inside Flutter WebView' }.

02 Install

Five ways to load the bridge

Pick the route that matches your project. The first three work today. The two bundle files arrive with the next release, and the README already documents them.

01

npm, with a project

Available now

Use this when your app already has a package.json. Import WebView from the package and each plugin from its file.

$npm install @yandeu/js-bridge

app.ts
import { WebView } from '@yandeu/js-bridge'
import { Vibration } from '@yandeu/js-bridge/lib/plugins/vibration.js'

if (WebView.isReady) {
  await WebView.statusBar.setColor('#000000')
}

document.getElementById('vibrate')?.addEventListener('click', () => {
  Vibration.vibrate()
})
02

A bundler of your choice

Available now

Any bundler works: esbuild, Vite, webpack or Rollup. The bundler packs your code and the modules it imports into one file, so the app runs offline. The plugins example uses esbuild.

terminal
# build www/index.ts into www/bundle.js
npx -y esbuild www/index.ts --bundle --outfile=www/bundle.js

# then zip the www folder and upload it to html2app.dev
zip -r app.zip www
03

ESM from esm.sh, no build

Available now

Import straight from the CDN in a module script. Good for a quick test. The browser fetches the modules at run time, so the app needs internet and fails offline.

index.html
<script type="module">
  import { WebView } from 'https://esm.sh/@yandeu/js-bridge@0.0.3'
  import { Share } from 'https://esm.sh/@yandeu/js-bridge@0.0.3/lib/plugins/share.js'

  WebView.navigationBar.setColor('#FF0000')
  document.getElementById('share-text').addEventListener('click', () => {
    Share.text('Hello')
  })
</script>
04

ESM bundle file

Next release

Download js-bridge.esm.min.js next to your page. It holds the core API and every plugin. Use js-bridge.esm.min.d.ts for TypeScript types. Serve the folder over HTTP, because browsers block module scripts opened from file://.

app.js
// @ts-check
// index.html loads this file with <script type="module" src="app.js"></script>
import { Vibration } from './js-bridge.esm.min.js'

document.getElementById('vibrate')?.addEventListener('click', () => {
  Vibration.vibrate(1000, 255)
})
05

UMD bundle file

Next release

A classic script tag that sets the global JsBridge. It works when you open the HTML file directly. The UMD file has no types, so use the ESM .d.ts for editor help.

index.html
<button id="vibrate">Vibrate</button>
<script src="js-bridge.umd.min.js"></script>
<script>
  const { WebView, Vibration } = JsBridge
  document.getElementById('vibrate').addEventListener('click', () => {
    Vibration.vibrate()
  })
</script>
Route Build step Internet at run time Best for
npm with a bundler Yes No Real apps with several files. The plugins example recommends it.
esm.sh No Yes Quick tests and prototypes.
ESM bundle file No No Plain modules, served over HTTP, with types.
UMD bundle file No No Plain HTML pages with a script tag. Opens from disk.

03 API

The core API at a glance

Everything hangs off the WebView object. Calls that talk to the app are async and resolve to a result object. Check ok before you read payload.

Call What it does
WebView.isReadyTrue once the bridge is connected inside the app.
WebView.isWebViewTrue when the user agent contains WebView.
await WebView.getPlatform()Returns 'android', 'ios', 'web' or 'unknown'.
WebView.fullscreen.enter() / exit()Turns fullscreen on or off. Fire and forget.
await WebView.statusBar.setColor('#RRGGBB')Sets the status bar color. #RRGGBBAA also works.
await WebView.statusBar.setIconsBrightness('light')Switches the status bar icons between 'light' and 'dark'.
await WebView.navigationBar.setColor('#RRGGBB')Sets the navigation bar color.
WebView.orientation.setPortrait() / setLandscape()Locks the screen orientation.
await WebView.persistentStorage.setItem(key, value)Stores a string under a key. Also getItem, removeItem and clear.
await WebView.deviceInfo() / packageInfo()Returns device or app details in the result's payload.
WebView.exitApp()Closes the app.
WebView.on(event, listener)Listens for an event that the app sends, such as a back button press. Also off and offMany.
WebView.destroy() / communication.init()Removes every listener and stops the bridge. Start it again with init().
usage.ts
import { WebView, communication } from '@yandeu/js-bridge'

if (WebView.isReady) {
  await WebView.statusBar.setIconsBrightness('light')

  const saved = await WebView.persistentStorage.setItem('token', 'abc123')
  const token = await WebView.persistentStorage.getItem('token')
  console.log(saved, token)
}

// Remove every listener when a component unmounts.
WebView.on('back', () => history.back())
// later:
WebView.destroy()
// and to start the bridge again:
communication.init()
  • Results, not exceptions. A failed call resolves to { ok: false, errorMessage }. Log the message, or show it to the user.
  • Some helpers return a boolean. The storage helpers return true or false and log the error themselves.
  • Events come from the app. The app emits an event name, and WebView.on runs your listener.

04 Plugins

Import only the plugins you use

Each plugin lives in its own file under lib/plugins/. The bundle files contain all of them, so the bundle is bigger than a single plugin import.

Vibration

lib/plugins/vibration.js

Buzz for a set time and strength, or play a pattern.

Share

lib/plugins/share.js

Open the native share sheet with text or a link.

In-App Browser

lib/plugins/inAppBrowser.js

Open a URL in the native browser instead of the app's WebView.

AdMob

lib/plugins/ads.js

Show banner, interstitial and rewarded ads.

Camera

lib/plugins/camera.js

Take a photo or record a video, with an optional time limit.

Microphone

lib/plugins/microphone.js

Record audio and get back a file for an audio element.

Image Picker

lib/plugins/imagePicker.js

Choose one or several images from the gallery.

File Picker

lib/plugins/filePicker.js

Choose any file, optionally limited to some extensions.

File Saver

lib/plugins/fileSaver.js

Save text, a Blob or a file through the system save dialog.

Turn plugins on in the dashboard

A plugin works only in an app that includes it. Choose plugins in the html2app dashboard before you build, because each build includes only the plugins you select. The native plugins page covers activation step by step.

05 FAQ

Common questions

The package and its example are on GitHub and npm.

Does the bridge work in a normal browser?
The page loads and runs. WebView.isReady stays false, and native calls return an error result instead of doing anything.
Why does the ESM bundle fail when I open the HTML file directly?
Browsers block module scripts loaded from file://. Serve the folder over HTTP, for example with python3 -m http.server, or use the UMD bundle, which works from disk.
Can the esm.sh import work offline?
No. The modules come from esm.sh each time the page loads. Use a bundler or a bundle file for an offline app.
Which version should I pin?
Pin the exact version you tested, such as @yandeu/js-bridge@0.0.3, in your import URLs and in package.json. The bundle files will ship with the next release.