鸿蒙 ArkUI 中使用 WebView

发布于:2025-03-30 ⋅ 阅读:(27) ⋅ 点赞:(0)

前言

在鸿蒙 ArkUI 开发中,有时候我们需要加载网页内容,比如嵌入 H5 页面、显示在线文档或加载 Web 应用。本文将介绍如何在 ArkUI 中使用 WebView 组件加载网页。

创建 WebView 组件

1. 基本使用

在 ArkUI 的 @Component 组件中,可以使用 Web 组件来加载网页。例如:

import { Web } from '@ohos/web';

@Entry
@Component
struct WebViewExample {
    build() {
        Column() {
            Web({
                src: 'https://www.example.com',
                controller: new WebController(),
                onPageStarted: (url: string) => {
                    console.info(`页面开始加载: ${url}`);
                },
                onPageFinished: (url: string) => {
                    console.info(`页面加载完成: ${url}`);
                },
                onError: (error: WebError) => {
                    console.error(`加载错误: ${error.message}`);
                }
            })
            .width('100%')
            .height('100%');
        }
    }
}

2. 使用 WebController 进行交互

如果需要更深入地控制 WebView,可以使用 WebController 进行操作,比如前进、后退、刷新等。

import { WebController } from '@ohos/web';

@Entry
@Component
struct WebViewWithControls {
    private webController: WebController = new WebController();

    build() {
        Column() {
            Web({
                src: 'https://www.example.com',
                controller: this.webController
            })
            .width('100%')
            .height('80%');
            
            Row() {
                Button('后退')
                    .onClick(() => this.webController.goBack());
                Button('前进')
                    .onClick(() => this.webController.goForward());
                Button('刷新')
                    .onClick(() => this.webController.reload());
            }
        }
    }
}

3. 处理 JavaScript 交互

ArkUI 的 WebView 组件支持 JavaScript 交互,可以使用 runJavaScript 方法执行 JavaScript 代码。

this.webController.runJavaScript('document.title', (result: string) => {
    console.info(`网页标题: ${result}`);
});

结语

通过 Web 组件,我们可以方便地在 ArkUI 中嵌入 Web 页面,并且可以通过 WebController 控制网页行为。希望这篇教程能帮助你更好地理解和使用鸿蒙的 WebView 组件!

如果有任何问题或更深入的需求,欢迎留言讨论!