文档管理中心

Web组件中如何通过手势滑动返回上一个Web页面

重写onBackPress函数,自定义返回逻辑,通过WebViewController提供的两种接口:accessBackward或accessStep(-1),都可以实现对web页面是否可以后退情况的判断,进而对web页面进行返回操作。参考代码如下:

收起
自动换行
深色代码主题
复制
  1. import { webview } from "@kit.ArkWeb";
  2. @Entry
  3. @Component
  4. struct PageOne {
  5. pageInfos: NavPathStack = new NavPathStack();
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. NavDestination() {
  9. Column() {
  10. Web({ src: 'https://www.XXX.com/', controller: this.controller }) // It needs to be manually replaced with the actual website
  11. }
  12. .width('100%')
  13. .height('100%')
  14. }
  15. .title('pageOne')
  16. .onBackPressed(() => {
  17. if (this.controller.accessBackward()) { // Determine whether the web page can be navigated back
  18. this.controller.backward() // Navigate back to the previous webpage
  19. return true
  20. } else {
  21. const popDestinationInfo = this.pageInfos.pop(); // Pop the top element of the routing stack
  22. return true;
  23. }
  24. }).onReady((context: NavDestinationContext) => {
  25. this.pageInfos = context.pathStack;
  26. })
  27. }
  28. }

参考链接

accessBackward

accessStep