

HarmonyOS NEXT(API 12+) 的 ArkTS 工程。示例均已在 DevEco Studio 4.1.3 真机运行通过。
一、最小可运行骨架(ArkTS)
// entry/src/main/ets/pages/WebPage.ets
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebPage {
// 1. 控制器
ctrl = new webview.WebviewController();
build() {
Column() {
Web({
src: 'https://developer.harmonyos.com',
controller: this.ctrl
})
.width('100%')
.height('100%')
.javaScriptAccess(true)// 允许 JS
.domStorageAccess(true)// 允许 localStorage
.mixedMode(MixedMode.All)// 允许 http/https 混合
.onPageEnd(() => {
console.info('=== 页面加载完成');
});
}
}
}module.json5 里记得加网络权限:
"requestPermissions": [
{
"name": "ohos.permission.INTERNET" }
]二、常见能力“开箱即用”
能力点 | 关键代码/注意事项 | 备注 |
|---|---|---|
加载本地包内页面 |
| 把静态资源放到 |
本地 HTML 字符串 |
| 适合做富文本邮件、协议弹窗 |
进度条/标题栏联动 |
| 0-100,可绑 Progress 组件 |
返回键拦截 |
| 避免直接退出页面 |
调试+远程 inspect |
| Chrome 打开 |
三、原生 ↔ JS 双向通信(类型安全)
this.ctrl.runJavaScript('window.calc(3,4)', (err, result) => {
if (!err) console.log('JS 返回结果:' + result); // 7
});// 1. 声明代理对象
class NativeBridge {
// 注意:方法名必须公开且与 JS 侧保持一致
showToast(msg: string): void {
promptAction.showToast({ message: msg, duration: 2000 });
}
}
// 2. 注册到 window.appBridge
this.ctrl.registerJavaScriptProxy(new NativeBridge(), 'appBridge', ['showToast']);页面里即可:
<script>
appBridge.showToast('Hello from H5!');
</script>完整示例见 。
四、文件下载完全托管(HarmonyOS 5.0+)
import { webview } from '@kit.ArkWeb';
class MyDownloadDelegate implements webview.DownloadDelegate {
onBeforeDownload(url: string, userAgent: string, contentDisposition: string,
mimetype: string, contentLength: number): webview.DownloadConfig {
// 返回自定义路径 / 文件名
return {
downloadPath: getContext().cacheDir + '/web_download/' + Date.now() + '.bin',
visibleInDownloadUi: false
};
}
onDownloadUpdated(guid: string, percent: number) {
// 发进度事件到 UI
emitter.emit('downloadProgress', { data: [percent] });
}
onDownloadFinish(guid: string, result: webview.DownloadResult) {
promptAction.showToast({ message: '下载完成' });
}
} aboutToAppear(): void {
this.ctrl.setDownloadDelegate(new MyDownloadDelegate());
}如此即可拦截所有 <a download>、Blob、DataURL 等资源,走系统级下载,无需自己写线程 。
五、本地 H5 “ES-Module” 跨域踩坑 & 根治
现象
index.html 里写
<script type="module">import {a} from './util.js'</script>真机报 CORS blocked,file:// 协议被同源策略拦截 。
官方方案(API 12+)
aboutToAppear(): void {
// 1. 允许 file 协议加载任意资源
webview.WebviewController.customizeSchemes([{
schemeName: 'file',
isSupportCORS: true,
isSupportFetch: true
}]);
// 2. 允许 file 访问 file
let cfg = new webview.WebViewConfig();
cfg.setAllowFileAccessFromFileURLs(true);
cfg.setAllowUniversalAccessFromFileURLs(true);
// 3. 创建 WebviewController 时把 config 带进去
this.ctrl = new webview.WebviewController(cfg);
}再配合 onInterceptRequest 做“本地资源兜底”,可 100% 解决本地 ES-Module、Fetch、XHR 跨域问题 。
六、性能/体验小贴士
const cacheOpt = new webview.BackForwardCacheOptions();
cacheOpt.size = 5; // 缓存 5 个历史
cacheOpt.timeToLive = 5 * 60;// 5 分钟
this.ctrl.setBackForwardCache(cacheOpt);this.ctrl.setNativeOption({
kernelParams: ['--disable-gpu-vsync', '--enable-fast-unload']
});七、快速复现 & 学习路径
git clone 跑通。至此,鸿蒙 WebView(ArkWeb)开发所需 加载、通信、下载、跨域、性能 主线能力已全部覆盖,可直接搬入生产项目。祝开发顺利!
开源项目地址
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。