DEV Community

lovehmos
lovehmos

Posted on

HarmonyOS Webview (ArkWeb) Hands-on Guide & Common Pitfalls

HarmonyOS Webview (ArkWeb) Hands-on Guide & Common Pitfalls

Introduction

Embedding web content is a common requirement in HarmonyOS app development. ArkWeb provides a powerful Webview component, making it easy for developers to integrate web browsing and H5 page interaction within their apps. This document summarizes core usage and common issues based on real development experience, helping you get started quickly.

Features

The main features of the Webview component:

  • Embed web content within the app
  • Control pages via WebviewController
  • Subscribe to Web engine initialization events with webview.once
  • Support Cookie synchronization, page navigation, forward/backward operations
  • Export current web content as a PDF file

Back/Forward Cache Settings (BackForwardCacheOptions)

Since API version 12, Webview supports back/forward page caching. Use the BackForwardCacheOptions class to set the number of cached pages and their lifetime, improving page switching smoothness.

  • size: Maximum number of cached pages per Webview. Default is 1, max is 50. 0 or negative disables caching.
  • timeToLive: Maximum seconds a page stays in cache. Default is 600. 0 or negative disables caching.
import { webview } from '@kit.ArkWeb';

const cacheOptions = new webview.BackForwardCacheOptions();
cacheOptions.size = 5; // Cache up to 5 pages
cacheOptions.timeToLive = 300; // Each page cached for up to 5 minutes

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController({
    backForwardCacheOptions: cacheOptions
  });

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

In practice, set cache size according to memory and business needs. Too much caching may affect performance.

Geolocation Permission Management (GeolocationPermissions)

Webview supports fine-grained geolocation permission management for web pages. Real device testing is required, and permissions such as ohos.permission.LOCATION must be requested.

  • Allow/delete geolocation permission for a specific origin
  • Query permission status (supports callback and Promise)
  • Get/clear all stored permissions
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();
  origin: string = "file:///";

  build() {
    Column() {
      Button('Allow Geolocation')
        .onClick(() => {
          try {
            webview.GeolocationPermissions.allowGeolocation(this.origin);
          } catch (error) {
            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
          }
        })
      Button('Check Permission')
        .onClick(() => {
          webview.GeolocationPermissions.getAccessibleGeolocation(this.origin)
            .then(result => {
              console.log('Permission status: ' + result);
            }).catch((error: BusinessError) => {
            console.error(`getAccessibleGeolocation error, ErrorCode: ${error.code},  Message: ${error.message}`);
          });
        })
      Button('Delete Permission')
        .onClick(() => {
          try {
            webview.GeolocationPermissions.deleteGeolocation(this.origin);
          } catch (error) {
            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
          }
        })
      Web({ src: 'https://www.example.com', controller: this.controller })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The origin parameter must be a valid origin string. Parameter type errors will return 401. If not authorized, the page cannot access geolocation.

Export Webpage to PDF (createPdf)

Webview supports exporting the current web content as a PDF file. Use the createPdf method of WebviewController to asynchronously obtain the PDF data stream of the web page.

  • configuration: PdfConfiguration object, sets PDF page width, height, margins, and whether to print background.
  • callback: Callback function, returns the PDF data stream.

Common issues:

  • WebviewController must be associated with a Web component, otherwise error 17100001 will occur.
  • Parameter type errors will return 401.
import { fileIo as fs } from '@kit.CoreFileKit';
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
  controller: webview.WebviewController = new webview.WebviewController();
  pdfConfig: webview.PdfConfiguration = {
    width: 8.27,
    height: 11.69,
    marginTop: 0,
    marginBottom: 0,
    marginRight: 0,
    marginLeft: 0,
    shouldPrintBackground: true
  }

  build() {
    Column() {
      Button('SavePDF')
        .onClick(() => {
          this.controller.createPdf(
            this.pdfConfig,
            (error, result: webview.PdfData) => {
              try {
                // Get component context
                let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
                // Get sandbox path and set PDF file name
                let filePath = context.filesDir + "/test.pdf";
                let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
                fs.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => {
                  console.info("createPDF write data to file succeed and size is:" + writeLen);
                }).catch((err: BusinessError) => {
                  console.error("createPDF write data to file failed with error message: " + err.message +
                    ", error code: " + err.code);
                }).finally(() => {
                  fs.closeSync(file);
                });
              } catch (resError) {
                console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
              }
            });
        })
      Web({ src: "www.example.com", controller: this.controller })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

In practice, make sure WebviewController is bound to a Web component first. It is recommended to save PDF files to the sandbox directory to avoid permission issues.

Usage Scenarios

  1. Embed H5 pages: Integrate third-party web pages, event pages, help centers, etc. within the app.
  2. Hybrid development: Implement some features with web technology to improve development efficiency.
  3. Data display: Dynamically display data or charts via web pages.

Pitfalls & Notes

  1. webview.once triggers only once: Only fires on the first load of the Web component. Pay attention to lifecycle management.
  2. DevEco Studio previewer does not support Webview: Always test on a real device to avoid misjudgment by the previewer.
  3. Strict parameter validation: webview.once will return error code 401 for parameter type errors. Check your arguments.
  4. Cookie sync timing: It is recommended to sync cookies after the webInited event, otherwise it may be invalid.
  5. Page navigation/refresh control: Use WebviewController for unified management to avoid state confusion.

Summary

The Webview component provides powerful web integration capabilities for HarmonyOS apps. Pay attention to lifecycle, event subscription, and parameter validation during development. Refer to official documentation and community experience when encountering issues. As the API continues to improve, the Webview experience will get even better.

References

Welcome to Try

If you are also developing HarmonyOS apps, feel free to use the Webview component. Hope it helps you!

Top comments (0)