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" }
]
二、常見能力“開箱即用”
| 能力點 | 關鍵代碼/注意事項 | 備註 |
|---|---|---|
| 加載本地包內頁面 | src: $rawfile('src/main/resources/rawfile/index.html') |
把靜態資源放到 rawfile 目錄即可 |
| 本地 HTML 字符串 | this.ctrl.loadData('Hello', 'text/html', 'UTF-8') |
適合做富文本郵件、協議彈窗 |
| 進度條/標題欄聯動 | .onProgressChange(e => this.curProgress = e.newProgress) |
0-100,可綁 Progress 組件 |
| 返回鍵攔截 | onBackPress():boolean{ if(this.ctrl.accessBackward()){this.ctrl.backward();return true} return false } |
避免直接退出頁面 |
| 調試+遠程 inspect | webview.WebviewController.setWebDebuggingAccess(true); 然後 PC 執行 hdc fport tcp:9222 tcp:9222 |
Chrome 打開 localhost:9222 即看到 WebView |
三、原生 ↔ JS 雙向通信(類型安全)
- ArkTS 調 JS
this.ctrl.runJavaScript('window.calc(3,4)', (err, result) => {
if (!err) console.log('JS 返回結果:' + result); // 7
});
- JS 調 ArkTS
// 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: '下載完成' });
}
}
- 綁定到 WebView
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']
});
- 預覽器 不支持 WebView,一切效果以 真機 為準 。
七、快速復現 & 學習路徑
- 將上面“最小骨架”複製到 Empty Ability 工程 → 真機運行 → 能出網頁即環境 OK。
- 再把“雙向通信”“下載託管”“本地 ES-Module”三段代碼分別貼進去驗證。
- 官方示例倉庫(Gitee) https://gitee.com/openharmony/arkweb_tutorial 已同步上述所有用法,可直接
git clone跑通。
至此,鴻蒙 WebView(ArkWeb)開發所需 加載、通信、下載、跨域、性能 主線能力已全部覆蓋,可直接搬入生產項目。祝開發順利!
[開源項目地址] https://gitee.com/lcmac/my-harmony-os