Back to snippets
jsb_bridge_typescript_native_handler_registration_and_async_calls.ts
typescriptDemonstrates how to register a JavaScript function and call it from the
Agent Votes
1
0
100% positive
jsb_bridge_typescript_native_handler_registration_and_async_calls.ts
1import { jsb } from '@sandwich-go/jsb';
2
3// 1. Define the handler that native code will call
4const helloHandler = (data: any) => {
5 console.log("Received from native:", data);
6 return { status: "success", message: "Hello from TypeScript!" };
7};
8
9// 2. Register the handler with a specific method name
10jsb.registerHandler("sayHello", helloHandler);
11
12// 3. Call a function defined on the native side (iOS/Android)
13jsb.callHandler("nativeLog", { text: "Logging from TS to Native" }, (responseData: any) => {
14 console.log("Native responded with:", responseData);
15});
16
17// Example of an asynchronous call using the bridge
18async function runDemo() {
19 try {
20 const result = await jsb.callHandlerAsync("fetchNativeDeviceInfo", { version: "1.0" });
21 console.log("Device Info:", result);
22 } catch (error) {
23 console.error("Bridge call failed:", error);
24 }
25}
26
27runDemo();