web拦截并替换图片?

如题:web拦截并替换图片?

阅读 3.7k
1 个回答

核心代码解释

主要为web组件的页面刷新,页面跳转,加载url,加载字符串等等。

import { webview } from '@kit.ArkWeb';
import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import axios from '@ohos/axios';

@Entry
@Component
struct GetFile {
  @State message: string = 'Hello World';
  // 获取应用文件路径
  context = getContext(this) as common.UIAbilityContext;
  webviewController: webview.WebviewController = new webview.WebviewController();
  responseweb: WebResourceResponse = new WebResourceResponse()

  aboutToAppear() {
    // 配置Web开启调试模式
    webview.WebviewController.setWebDebuggingAccess(true);
  }

  hasFile(filePath: string) {
    let b = fs.accessSync(filePath)
    return b
  }

  async getFile(url: string) {
    // const regex = new RegExp('/[^/]+/g', 'gim');
    // console.log(url+" 123456")
    // const fileName = url.match(regex);
    const fileName = url.split("/").pop();
    console.log(fileName + " 123456")
    const filePath = this.context.cacheDir + '/' + fileName;
    console.log(filePath + ' 123456')
    const flag = this.hasFile(filePath);
    console.log(flag + "123456")
    if (!flag) {
      await this.downloadImage(url, filePath);
    }
    // const fd : number = await fileio.open(filePath);
    let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
    console.log(file + "1234567")
    let arrayBuffer = new ArrayBuffer(4096);
    console.log(file.fd + " 123456")
    return file.fd;
  }

  async downloadImage(url: string, filePath: string) {
    try {
      await axios({
        method: "get",
        url,
        context: this.context,
        filePath: filePath
      });
    } catch (error) {
      console.error('[Demo] axios error');
    }
  }

  build() {
    Column() {
      Web({ src: $rawfile('catch.html'), controller: this.webviewController })
        .onInterceptRequest((event) => {
          if (event) {
            console.log('url123456:' + event.request.getRequestUrl())
          }
          const url = event!.request.getRequestUrl();
          // const regExp = new RegExp("^(http|https)[w/-]+(.jpg)$");
          console.log(url.endsWith(".jpg") + '123456')
          if (!url.endsWith(".jpg")) return null;
          try {
            // const responseweb = new WebResourceResponse();
            let url2 = 'https://img.tukuppt.com/photo-big/17/12/16/57/94/171216579483.jpg';
            this.getFile(url2).then(fd => {
              this.responseweb.setResponseData(fd);
              this.responseweb.setResponseCode(200);
              this.responseweb.setReasonMessage('OK');
              this.responseweb.setResponseIsReady(true);
              console.log(fd + " 1234567")
            });
            this.responseweb.setResponseMimeType('image/*');
            this.responseweb.setResponseIsReady(false);
            console.log(this.responseweb.getResponseData().toString + "123456")
            return this.responseweb;
          } catch (error) {
            console.error(`[Demo]Code: ${error.code},Message: ${error.message} `);
            return null
          }
        })
    }
  }
}

上诉是web拦截并替换图片,对于web拦截并替换资源,可以参考一下

实现效果

web拦截并替换图片,对于web拦截并替换资源,对违规图片或不想要的图片进行替换。

logo
HarmonyOS
子站问答
访问
宣传栏