参考demo:import web_webview from '@ohos.web.webview' import { window } from '@kit.ArkUI' import { common } from '@kit.AbilityKit' @Entry @Component struct Index { @State newsUrl: string = 'xxx' @State webHeight: Length = '100%' controller: WebviewController = new web_webview.WebviewController() handler: FullScreenExitHandler | null = null // 当设备横屏时条件成立 @State isFullScreen:boolean = false; // 改变设备横竖屏状态函数 private changeOrientation(isLandscape: boolean) { this.isFullScreen = isLandscape // 获取UIAbility实例的上下文信息 let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // 调用该接口手动改变设备横竖屏状态 window.getLastWindow(context).then((lastWindow) => { lastWindow.setWindowLayoutFullScreen(isLandscape) lastWindow.setPreferredOrientation(isLandscape ? window.Orientation.LANDSCAPE : window.Orientation.PORTRAIT) }); } //对于NavPathStack的页面,就用NavDestination(){}.onBackPressed监听,对于router跳转的页面,就用onBackPress()监听 onBackPress():boolean { if(!this.isFullScreen) { //不是全屏,就执行返回上一页的逻辑 if (this.controller.accessBackward()) { this.controller.backward(); // 返回上一个h5页 // 执行用户自定义返回逻辑 return true; } else { // 执行系统默认返回逻辑,返回上一个page页 return false; } } else { //是全屏,就退出全屏 if (this.handler) { this.handler.exitFullScreen() } return true } } build() { Column() { Column() { Web({ controller: this.controller, src: this.newsUrl, renderMode: 1 }) .width('100%') .backgroundColor(Color.White) .height(this.webHeight) .onPageEnd(() => { setTimeout(() => { if (this.controller != null) { try { this.webHeight = this.isFullScreen ? '100%' : this.controller.getPageHeight() } catch (e) { } } }, 1500) }) .onFullScreenEnter((event) => { console.log("onFullScreenEnter...") this.handler = event.handler this.changeOrientation(true); }) .onFullScreenExit(() => { console.log("onFullScreenExit...") if (this.handler) { this.handler.exitFullScreen() this.changeOrientation(false); } }) .layoutMode(this.isFullScreen ? WebLayoutMode.NONE : WebLayoutMode.FIT_CONTENT) .mixedMode(MixedMode.All) Text('文本内容') .width('100%') .height(100) .textAlign(TextAlign.Center) .fontColor(Color.Brown) .backgroundColor(Color.Gray) } .width('100%') this.bottomToolBar() } .justifyContent(FlexAlign.SpaceBetween) .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM]) .height('100%') .width('100%') } @Builder bottomToolBar() { Column() { Divider() .color($r('app.color.Color_EBEBEB')) .strokeWidth(1) Text('说点什么...') .fontColor('#a9a9a9') .fontSize(14) .borderRadius(6) .backgroundColor($r('app.color.Color_F0F0F0')) .height(36) .layoutWeight(1) .margin({ top: 6, bottom: 6 }) .padding({ left: 14 }) }.width('100%') .height(48) .backgroundColor($r('app.color.Color_F5F5F5')) } }
参考demo: