DEV Community

Cover image for The front-end page calls the application-side function
liu yang
liu yang

Posted on

The front-end page calls the application-side function

Integrating Application Code with Frontend Pages in HarmonyOS Next

Registering Application-Side Code to Frontend Pages

To enable the frontend page to call application-side functions, developers can register application-side code to the frontend page using the Web component. Once registered, the frontend can invoke these functions using the registered object name.

Registration Methods

There are two ways to register application-side code:

  1. During Web Component Initialization: Using the javaScriptProxy() interface.
  2. After Web Component Initialization: Using the registerJavaScriptProxy() interface. This method should be used in conjunction with deleteJavaScriptRegister() to prevent memory leaks.

Example: Using javaScriptProxy()

// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

class TestClass {
  constructor() {}

  test(): string {
    return 'ArkTS Hello World!';
  }
}

@Entry
@Component
struct WebComponent {
  webviewController: webview.WebviewController = new webview.WebviewController();
  @State testObj: TestClass = new TestClass();

  build() {
    Column() {
      Button('Delete JavaScript Register')
        .onClick(() => {
          try {
            this.webviewController.deleteJavaScriptRegister("testObjName");
          } catch (error) {
            console.error(`Error Code: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
          }
        })
      Web({ src: $rawfile('index.html'), controller: this.webviewController })
        .javaScriptProxy({
          object: this.testObj,
          name: "testObjName",
          methodList: ["test"],
          controller: this.webviewController,
          asyncMethodList: [],
          permission: '{"javascriptProxyPermission":{"urlPermissionList":[{"scheme":"resource","host":"rawfile","port":"","path":""},' +
                      '{"scheme":"e","host":"f","port":"g","path":"h"}],"methodList":[{"methodName":"test","urlPermissionList":' +
                      '[{"scheme":"https","host":"xxx.com","port":"","path":""},{"scheme":"resource","host":"rawfile","port":"","path":""}]},' +
                      '{"methodName":"test11","urlPermissionList":[{"scheme":"q","host":"r","port":"","path":"t"},' +
                      '{"scheme":"u","host":"v","port":"","path":""}]}]}}'
        })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Example: Using registerJavaScriptProxy()

// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

class TestClass {
  constructor() {}

  test(): string {
    return 'ArkUI Web Component';
  }

  toString(): void {
    console.log('Web Component toString');
  }
}

@Entry
@Component
struct Index {
  webviewController: webview.WebviewController = new webview.WebviewController();
  @State testObj: TestClass = new TestClass();

  build() {
    Column() {
      Button('Refresh')
        .onClick(() => {
          try {
            this.webviewController.refresh();
          } catch (error) {
            console.error(`Error Code: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
          }
        })
      Button('Register JavaScript to Window')
        .onClick(() => {
          try {
            this.webviewController.registerJavaScriptProxy(
              this.testObj,
              "testObjName",
              ["test", "toString"],
              [],
              '{"javascriptProxyPermission":{"urlPermissionList":[{"scheme":"resource","host":"rawfile","port":"","path":""},' +
              '{"scheme":"e","host":"f","port":"g","path":"h"}],"methodList":[{"methodName":"test","urlPermissionList":' +
              '[{"scheme":"https","host":"xxx.com","port":"","path":""},{"scheme":"resource","host":"rawfile","port":"","path":""}]},' +
              '{"methodName":"test11","urlPermissionList":[{"scheme":"q","host":"r","port":"","path":"t"},' +
              '{"scheme":"u","host":"v","port":"","path":""}]}]}}'
            );
          } catch (error) {
            console.error(`Error Code: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
          }
        })
      Button('Delete JavaScript Register')
        .onClick(() => {
          try {
            this.webviewController.deleteJavaScriptRegister("testObjName");
          } catch (error) {
            console.error(`Error Code: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
          }
        })
      Web({ src: $rawfile('index.html'), controller: this.webviewController })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Permission Configuration

The optional permission parameter is a JSON string that defines the permissions for the JavaScript proxy. Here's an example:

{
  "javascriptProxyPermission": {
    "urlPermissionList": [
      {
        "scheme": "resource",
        "host": "rawfile",
        "port": "",
        "path": ""
      },
      {
        "scheme": "https",
        "host": "xxx.com",
        "port": "8080",
        "path": "a/b/c"
      }
    ],
    "methodList": [
      {
        "methodName": "test",
        "urlPermissionList": [
          {
            "scheme": "https",
            "host": "xxx.com",
            "port": "",
            "path": ""
          },
          {
            "scheme": "resource",
            "host": "rawfile",
            "port": "",
            "path": ""
          }
        ]
      },
      {
        "methodName": "test11",
        "urlPermissionList": [
          {
            "scheme": "q",
            "host": "r",
            "port": "",
            "path": "t"
          },
          {
            "scheme": "u",
            "host": "v",
            "port": "",
            "path": ""
          }
        ]
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Frontend Page Implementation

<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
    <button type="button" onclick="callArkTS()">Click Me!</button>
    <p id="demo"></p>
    <script>
        function callArkTS() {
            let str = testObjName.test();
            document.getElementById("demo").innerHTML = str;
            console.info('ArkTS Hello World! :' + str);
        }
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)