前言

在公司应用鸿蒙化的过程中,翻看原来Android的代码,发现在webview中有拦截前端请求,原生侧自己做处理,然后返回给前端的情况,代码比较老,也说不清楚是哪些前端工程里面在使用,只能暂时先按照Android的逻辑移植到鸿蒙上了

大致流程

  1. 拦截请求:当Web组件加载URL之前,会触发onInterceptRequest回调,开发者可以在此回调中拦截请求并返回自定义的响应数据。

  2. 构造响应数据:开发者可以构造一个WebResourceResponse对象,设置响应数据、编码格式、MIME类型、状态码等信息。

  3. 返回响应:将构造好的WebResourceResponse对象返回给Web内核,Web内核会根据此响应信息进行页面资源加载。

实现

前端页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<!-- 页面资源请求 -->
<div style="font-size:60px"> <a href="https://target.do">intercept test!</a> </div>

<div style="font-size:60px">
<a href="https://developer.huawei.com/consumer/cn/develop/">不被拦截的跳转</a>
</div>
</body>
</html>

在鸿蒙端

// xxx.ets
import { webview } from '@kit.ArkWeb';


@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();
  responseResource: WebResourceResponse = new WebResourceResponse();
  // 开发者自定义响应数据
  @State webData: string = '<!DOCTYPE html>\n' +
    '<html>\n' +
    '<head>\n' +
    '<title>intercept test</title>\n' +
    '</head>\n' +
    '<body>\n' +
    '<h1>intercept ok</h1>\n' +
    '</body>\n' +
    '</html>'


  build() {
    Column() {
      Web({ src: $rawfile('index.html'), controller: this.controller })
          .onInterceptRequest((event) => {
            if (event) {
              console.info('url:' + event.request.getRequestUrl());
              // 拦截页面请求
              if (event.request.getRequestUrl() !== 'https://target.do/') {
                return null;
              }
            }
            // 构造响应数据
            this.responseResource.setResponseData(this.webData);
            this.responseResource.setResponseEncoding('utf-8');
            this.responseResource.setResponseMimeType('text/html');
            this.responseResource.setResponseCode(200);
            this.responseResource.setReasonMessage('OK');
            return this.responseResource;
          })
    }
  }
}

效果

img

可以看到,当我们点击intercept test!的适合,我们拦截了请求并且返回了我们自定义的数据。
点击不被拦截的跳转时,正常跳转到了对应页面

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐