HarmonyOS Web控件onLoadIntercept怎么区分拦截的url是当前页面还是新页面?

Web有一个onLoadIntercept拦截请求的url,但需要区分是当前页面还是新开的页面。目的是当前页面不处理,但新开页面需要跳转到新的Page页面。

阅读 490
1 个回答

请参考如下demo:

import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  @State loadUrl: string | null = null
  build() {
    Column() {
      Web({ src: 'xxx', controller: this.controller })
        .onLoadIntercept((event) => {

          if (this.loadUrl == null) //判断首次加载
          {
            console.log("loginfo:首次加载")
            this.loadUrl = event.data.getRequestUrl()
          }

          if (this.loadUrl != event.data.getRequestUrl() && this.loadUrl != null) //非首次加载判断
          {
            console.log("loginfo:两次url不一样—上次加载url:" + (this.loadUrl == null ? null : this.loadUrl) +
              "----本次加载URL:" + event.data.getRequestUrl()) //打印加载url 可以删掉
            this.loadUrl = event.data.getRequestUrl() //将此次加载路径保存入变量中,为下次对比做参照

            if (event.data.isRedirect()) //判断服务器重定向
            {
              console.log("loginfo:服务器重定向")
            } else {
              if (event.data.isRequestGesture()) //判断是否发生了交互,未交互就跳转认定为代码重定向,发生了交互认定为正常页面跳转
              {
                console.log("loginfo:页面跳转") //,用户交互发生的页面跳转属于正常页面跳转,不属于重定向
              } else {
                console.log("loginfo:客户端页面代码重定向") //若未发生交互,直接进行页面跳转则认定发生了重定向
              }
            }
          } else {
            console.log("两次url相同,未生重定向") //两次url相同,为发生重定向
          }
          return false
        })
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进