背景
HarmonyOS平台通过Web控件可支持网页加载展示,Web在HarmonyOS官方指导中是作为专项介绍的。
本篇文章将从Android和iOS平台研发角度出发来实践学习API功能
说明
- 整个示例是以HarmonyOS开发文档网址作为加载目标
- 页面布局增加了三个按钮“后退”,“前进”, “刷新”
效果

准备
- 请参照官方指导,创建一个Demo工程,选择Stage模型
- 熟读HarmonyOS Web组件指导 developer.harmonyos.com/cn/docs/doc…
实践总结
- UA可以设置,但无法通过API拿到自己设置的UA值
- 文件可以下载,但用户没有控制权
- 用户无法控制定位权限申请
- Web控件当前需要将UA设置为Android或者iOS特征的UA,大部分主流网站没有适配鸿蒙Web
- 鸿蒙UA特征不明显 Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.88 Mobile Safari/537.36
开始
页面容器设置为沉浸式
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
// 1.获取应用主窗口。
let windowClass: window.Window = null;
windowStage.getMainWindow((err, data) => {
if (err.code) {
console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
return;
}
windowClass = data;
console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
// 2.实现沉浸式效果:设置导航栏、状态栏显示。
windowClass.setWindowSystemBarEnable(['status','navigation'], (err) => {
if (err.code) {
console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the system bar to be visible.');
});
})
//获取当前应用内最后显示的窗口,使用callback异步回调
window.getLastWindow(this.context).then((result: window.Window) => {
result.setWindowSystemBarEnable(['status', 'navigation'])
result.setWindowLayoutFullScreen(true);
})
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
});
}
}
复制复制
创建WebView组件
文件路径
根目录/ets/entry/src/main/pages/WebView.ts
注册页面 main_pages.json
{
"src": [
"pages/Index"
,"pages/WebView"
]
}
功能介绍
- 支持多窗口
- 多窗口返回关闭
- 加载进度提示
- 警告框,确认框,提示框
- 权限申请
- 输出调试日志
- 非http或https协议拦截
import web_webview from '@ohos.web.webview';
import router from '@ohos.router';
import common from '@ohos.app.ability.common';
import Url from '@ohos.url'
web_webview.once("webInited", () => {
console.log("setCookie")
web_webview.WebCookieManager.setCookie("https://developer.harmonyos.com/", "author=harvey")
})
//在同一page页有两个web组件。在WebComponent新开窗口时,会跳转到NewWebViewComp。
@CustomDialog
struct NewWebViewComp {
private controller?: CustomDialogController
private webv


被折叠的 条评论
为什么被折叠?



