DEV Community

HarmonyOS
HarmonyOS

Posted on

Use of JSBridge in HarmonyOS Client

Read the original article:Use of JSBridge in HarmonyOS Client

Use of JSBridge in HarmonyOS Client

Problem description

In hybrid application development, efficient interaction between web pages and system functions is a core requirement, requiring:

Web pages call system functions (such as obtaining device information and calling system APIs);
System code calls back to the web page;
Establish a stable and reliable two-way communication mechanism.

Background knowledge

In the HarmonyOS system, the traditional JSBridge implementation method is converted into the JSProxy mechanism. This change brings some technical challenges and problems.

API compatibility issues:
Traditional JSBridge methods may not be used directly in HarmonyOS.
Some bridging logic needs to be rewritten to adapt to the JSProxy mechanism.

Differences in communication mechanisms:
JSBridge is usually based on URL Scheme or iframe.
JSProxy uses a more efficient Native binding method.
Changes in the underlying mechanism may cause the original communication mode to fail.

Security restrictions are enhanced:
HarmonyOS's JSProxy has stricter restrictions on cross-domain access.
The security policy needs to be reconfigured.

Debugging becomes more difficult:
The call stack of JSProxy is not as intuitive as the traditional JSBridge.
Inadequate support for error tracking and debugging tools.

Solution

Declare the injected system-side object:

import { webview } from '@kit.ArkWeb';

/**
 * JSBridge object exposed to the Web by the system
* @property {string} name - user name
* @property {number} age - user age
 */
class JSBridge {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  /**
  * Test method example
   */
  helloWorld() {
    console.log("JSBridge连接成功");
  }

  /**
 * Get username
 * @returns {string} current username
   */
  getUserName(): string {
    return this.name;
  }

  /**
  * Print object information
  */
   toString(): void {
   console.log(`JSBridge instance: name=${this.name}, age=${this.age}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Register JavaScript proxy objects. Two registration methods are recommended:

Method 1: Use registerJavaScriptProxy (recommended)

@Entry
@Component
struct WebComponent {
  private controller: webview.WebviewController = new webview.WebviewController();
  private jsBridge: JSBridge = new JSBridge("Harmony", 3);

  build() {
    Column() {
      Web({
        src: "https://example.com", //Replace with the actual H5 page address
        controller: this.controller
      })
      .onControllerAttached(() => {
        // Register the JSBridge object
        this.controller.registerJavaScriptProxy(
           this.jsBridge, // Object to be injected
           'HarmonyBridge', // Global object name in H5
           ['helloWorld', 'getUserName'] // List of exposed methods
        );

        console.log('JSBridge registration completed');
      })
    }
    .width('100%')
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Web-side calling method:

// Call system method
   try {
// Simple method call
   HarmonyBridge.helloWorld();

// Get return value
   const userName = HarmonyBridge.getUserName();
   console.log('Get user name:', userName);

} catch (error) {
   console.error('JSBridge call failed:', error);
}

// Security call check
if (window.HarmonyBridge && typeof HarmonyBridge.getUserName === 'function') {
   // ...
}
Enter fullscreen mode Exit fullscreen mode

Through the above solution, efficient and stable communication between HarmonyOS applications and web pages can be achieved, meeting various needs of hybrid development.

Written by Emine Inan

Top comments (0)