How To Write A JS-SDK

A JavaScript SDK (JS-SDK) is a software development kit that enables web applications to interact with native mobile device functionality through JavaScript. It acts as a bridge between web code running in a browser/WebView and native device features like:

  • Camera access
  • Contact list
  • Location services
  • File system
  • Device sensors
  • And other platform-specific capabilities

The SDK provides a JavaScript API that web developers can use to seamlessly integrate native functionality, while handling the complex communication between the web and native layers behind the scenes.

Here is simple concepts about how to write a SDK.

1. Web layer

  • In web layer, we should bind the function to window environment.
Code

(function () {
  const sdk = {
    callNative(action, data = {}) {
      const message = JSON.stringify({ action, data });

      // Android WebView bridge
      if (window.AndroidInterface && typeof window.AndroidInterface.postMessage === 'function') {
        window.AndroidInterface.postMessage(message);
      }

      // iOS WKWebView bridge
      else if (
        window.webkit &&
        window.webkit.messageHandlers &&
        window.webkit.messageHandlers.nativeBridge &&
        typeof window.webkit.messageHandlers.nativeBridge.postMessage === 'function'
      ) {
        window.webkit.messageHandlers.nativeBridge.postMessage({ action, data });
      }

      // Unsupported platform
      else {
        console.warn("Native bridge not available");
      }
    },

    openCamera(options = {}) {
      // You can pass options like cameraType: 'front' | 'back'
      this.callNative("openCamera", options);
    },
  };

  // Assign to window
  window.sdk = sdk;
})();

2. Native Layer

2.1. Android (Kotlin Example)

Code

@JavascriptInterface
fun postMessage(json: String) {
    val obj = JSONObject(json)
    val action = obj.getString("action")

    when (action) {
        "openCamera" -> {
            // Call your Android native camera code here
            openCamera()
        }
    }
}

webView.addJavascriptInterface(MyInterface(this), "AndroidInterface")

2.2. iOS (Swift WKWebView)

Code

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    if message.name == "nativeBridge", let body = message.body as? [String: Any] {
        if let action = body["action"] as? String, action == "openCamera" {
            openCamera()
        }
    }
}


webView.configuration.userContentController.add(self, name: "nativeBridge")

3. Web usage

Code

window.sdk.openCamera({ cameraType: 'back' });

Last Updated On April 13, 2025