Webview页面中,如何拦截从网络请求来的数据,转为读取本地预置数据 HarmonyOS 鸿蒙Next

Webview页面中,如何拦截从网络请求来的数据,转为读取本地预置数据 HarmonyOS 鸿蒙Next

Web组件支持在应用拦截到页面请求后自定义响应请求能力。开发者通过onInterceptRequest()接口来实现自定义资源请求响应 。自定义请求能力可以用于开发者自定义Web页面响应、自定义文件资源响应等场景。

在下面的示例中,Web组件通过拦截页面请求"https://www.example.com/test.js",应用侧代码构建响应资源,从而转为读取本地预置数据,本示例用到网络资源,需要申请"ohos.permission.INTERNET"权限,具体配置步骤请参考声明权限。

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

@Entry
@Component
struct HomePage { 
  private textInfo: string = '当前页面数据:'; 
  @State resourceStatus: string = '非本地预置数据'; 
  controller: webview.WebviewController = new webview.WebviewController(); 
  responseResource: WebResourceResponse = new WebResourceResponse(); 
  // 开发者自定义响应数据 
  // myImage.src和myVideo.src后的赋值数据都是本地预置数据,存放在项目entry/src/main/resources/rawfile/resourceData目录下。 
  @State jsData: string = 'let myText = window.document.getElementById("my-text");\n' + 
    'let myImage = window.document.getElementById("my-img");\n' + 
    'let myVideo = window.document.getElementById("my-video");\n' + 
    'myText.innerHTML = "Locally preconfigured text resources";\n' + 
    'myImage.src = "../resourceData/startIcon.png";\n' + 
    'myVideo.src = "../resourceData/video.mp4";\n'; 

  build() { 
    Column { 
      Text(`${this.textInfo}${this.resourceStatus}`) 
        .font({ size: 20, weight: FontWeight.Bold }) 
      Web({ src: $rawfile('webPage.html'), controller: this.controller }) 
        .onInterceptRequest((event) => { 
          // 拦截页面请求,当请求包含'https://www.example.com/test.js'时,页面数据使用本地预置数据,此处逻辑根据实际情况而定。 
          if (event?.request.getRequestUrl() === 'https://www.example.com/test.js') { 
            this.resourceStatus = '本地预置数据'; 
            // 构造响应数据 
            this.responseResource.setResponseHeader([ 
              { 
                headerKey: "ResponseDataID", 
                headerValue: "0000000000001" 
              }]);
            this.responseResource.setResponseData(this.jsData); // 使用本地预置数据 
            this.responseResource.setResponseEncoding('utf-8'); 
            this.responseResource.setResponseMimeType('application/javascript'); 
            this.responseResource.setResponseCode(200); 
            this.responseResource.setReasonMessage('OK'); 
            return this.responseResource; 
          } 
          return null; 
        }) 
    } 
  } 
}
<!-- src/main/resources/rawfile/webPage.html --> 
<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
</head> 
<body> 
    <div style="text-align: center;width: 100%;"> 
        <h1 id="my-text">Simulating Large Text Resources</h1> 
        <!--    img里的src填写图片地址,可以是网络图片    --> 
        <img id="my-img" style="margin: 10% 0; min-width: 100px;min-height: 100px;" src=""> 
        <video id="my-video" width="100%" controls> 
            <!--    source里的src填写mp4格式的地址,可以是网络视频    --> 
            <source src="" type="video/mp4"> 
        </video> 
    </div> 
    <script src="https://www.example.com/test.js"></script> 
</body> 
</html>

更多关于Webview页面中,如何拦截从网络请求来的数据,转为读取本地预置数据 HarmonyOS 鸿蒙Next的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于Webview页面中,如何拦截从网络请求来的数据,转为读取本地预置数据 HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,可以通过自定义WebResourceResponse来拦截网络请求并返回本地预置数据。具体步骤如下:

  1. 实现WebViewClient的子类,并重写shouldInterceptRequest方法。
  2. shouldInterceptRequest方法中,根据请求的URL判断是否需要拦截。
  3. 若需要拦截,读取本地预置数据并构造WebResourceResponse对象返回。

示例代码如下:

import webview from '@ohos.web.webview';
import fileIo from '@ohos.fileio';

class CustomWebViewClient extends webview.WebViewClient {
    shouldInterceptRequest(webView: webview.WebView, request: webview.WebResourceRequest): webview.WebResourceResponse | null {
        if (request.getUrl().toString().endsWith('example.json')) {
            try {
                const filePath = 'entry/resources/rawfile/example.json';
                const file = fileIo.openSync(filePath, fileIo.OpenMode.READ_ONLY);
                const buffer = fileIo.readSync(file.fd, { offset: 0, length: 1024 });
                fileIo.closeSync(file.fd);
                return new webview.WebResourceResponse('application/json', 'UTF-8', buffer);
            } catch (error) {
                console.error('Error reading local file:', error);
            }
        }
        return null;
    }
}

const webView: webview.WebView = webview.createWebView();
webView.setWebViewClient(new CustomWebViewClient());

此代码拦截了请求example.json的URL,并返回本地预置的JSON文件数据。

回到顶部