HarmonyOS 鸿蒙Next web加载应用沙盒.filesDir+"/JYLocalH5/"下的Vue打包文件,在onInterceptRequest做了映射后白屏,怎么解决?

发布于 1周前 作者 caililin 来自 鸿蒙OS

HarmonyOS 鸿蒙Next web加载应用沙盒.filesDir+"/JYLocalH5/"下的Vue打包文件,在onInterceptRequest做了映射后白屏,怎么解决?

web加载应用沙盒.filesDir+"/JYLocalH5/"下的Vue打包文件,在onInterceptRequest做了映射,但是白屏 加载项目资源目中的Vue项目通过映射response.setResponseData($rawfile(xxx));可以成功加载 但是加载沙盒中的vue项目不可以,映射时通过setResponseData(arrybuffer) 请问怎么解决
2 回复

针对您的问题,您可以进行如下步骤:

import { webview } from '@kit.ArkWeb';
import { common } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit';
import { BusinessError, zlib } from '@kit.BasicServicesKit';
import { RawFileDescriptor } from './WebImagePage';
import { FileUtil } from '@pura/harmony-utils';
import fs from '@ohos.file.fs';
import { buffer } from '@kit.ArkTS';

@Entry
@Component
struct WebVuePage {
  @State message: string = 'Hello World';
  controller: webview.WebviewController = new webview.WebviewController();
  context = getContext(this) as common.UIAbilityContext;
  filesDir = this.context.filesDir;
  @State show: boolean = false;
  schemeMapSha = new Map([
    ["https://www.example.com/dist/index.html", "dist/index.html"],
    ["https://www.example.com/assets/index-CdZkYDST.js", 'dist/assets/index-CdZkYDST.js'],
    ["https://www.example.com/assets/index-CBy-tPLh.css", 'dist/assets/index-CBy-tPLh.css'],
    ["https://www.example.com/dist/index.html#/home", "dist/index.html"],
    ["https://www.example.com/assets/index-DEaf4dPO.js", "dist/assets/index-DEaf4dPO.js"],
    ["https://www.example.com/assets/index-CBy-tPLh.css", "dist/assets/index-CBy-tPLh.css"],
    ["https://www.example.com/assets/AboutView-Dc7Uu0nQ.js", "dist/assets/AboutView-Dc7Uu0nQ.js"],
    ["https://www.example.com/assets/AboutView-C6Dx7pxG.css", "dist/assets/AboutView-C6Dx7pxG.css"],
    ["https://www.example.com/dist/assets/AboutView-CSLU876L.js", "dist/assets/AboutView-CSLU876L.js"],
    ["https://www.example.com/assets/AboutChild-B4t3HCqG.js", "dist/assets/AboutChild-B4t3HCqG.js"],
    ["https://www.example.com/assets/AboutView-P0x6aoHb.js", "dist/assets/AboutView-P0x6aoHb.js"],
    ["https://www.example.com/assets/AboutChild-CMguLNki.js", "dist/assets/AboutChild-CMguLNki.js"],
    ["https://www.example.com/assets/index-BzBjVdyO.js", "dist/assets/index-BzBjVdyO.js"],
    ["https://www.example.com/assets/test-B4w1tkP8.mp4", "dist/assets/test-B4w1tkP8.mp4"],
    ["https://www.example.com/assets/AboutView-BMur5onV.js", "dist/assets/AboutView-BMur5onV.js"],
    ["https://www.example.com/assets/AboutChild-CUcxJpMY.js", "dist/assets/AboutChild-CUcxJpMY.js"],
    ["https://www.example.com/assets/mmmm-6R9i91gc.png", "dist/assets/mmmm-6R9i91gc.png"],
    ["https://www.example.com/assets/test_jpeg-BjZOxgOX.jpg", "dist/assets/test_jpeg-BjZOxgOX.jpg"],
  ]);
  mimeTypeMapSha = new Map([
    ['dist/index.html', 'text/html'],
    ['dist/assets/index-CdZkYDST.js', 'text/javascript'],
    ['dist/assets/index-CBy-tPLh.css', "text/css"],
    ["dist/assets/AboutView-Dc7Uu0nQ.js", "text/javascript"],
    ["dist/assets/AboutView-C6Dx7pxG.css", "text/css"],
    ["dist/assets/AboutChild-B4t3HCqG.js", "text/javascript"],
    ["dist/assets/AboutView-P0x6aoHb.js", "text/javascript"],
    ["dist/assets/AboutChild-CMguLNki.js", "text/javascript"],
    ["dist/assets/index-BzBjVdyO.js", "text/javascript"],
    ["dist/assets/AboutView-BMur5onV.js", "text/javascript"],
    ["dist/assets/AboutChild-CUcxJpMY.js", "text/javascript"],
    ["dist/assets/mmmm-6R9i91gc.png", "image/png"],
    ["dist/assets/test_jpeg-BjZOxgOX.jpg", "image/jpeg"],
    ["dist/assets/test-B4w1tkP8.mp4", "video/mp4"],
  ])

  async copy2file(item: RawFileDescriptor) {
    try {
      let data = this.context.filesDir;
      let dstPath = data + '/dist.zip'
      this.saveFileToCache(item, dstPath)
      console.log('success')
    } catch (e) {
      console.log(`RawFile#copy2file() error : ${JSON.stringify(e)}`)
    }
  }

  saveFileToCache(file: RawFileDescriptor, path: string) {
    let cacheFile = fileIo.openSync(
      path,
      fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE | fileIo.OpenMode.TRUNC)
    let buffer = new ArrayBuffer(4096);
    let currentOffset = file.offset;
    let lengthNeedToReed = file.length;
    let readOption: RawFileDescriptor = {
      offset: currentOffset,
      length: lengthNeedToReed > buffer.byteLength ? 4096 : lengthNeedToReed
    }
    while (true) {
      let readLength = fileIo.readSync(file.fd, buffer, readOption);
      fileIo.writeSync(cacheFile.fd, buffer, { length: readLength })
      if (readLength < 4096) {
        break;
      }
      lengthNeedToReed -= readLength;
      readOption.offset += readLength;
      readOption.length = lengthNeedToReed > buffer.byteLength ? 4096 : lengthNeedToReed;
    }
    fileIo.close(cacheFile);
  }

  testUnCompressZip() {
    const inFile = this.context.filesDir + '/dist.zip';
    const outFileDir = this.context.filesDir;
    try {
      zlib.decompressFile(inFile, outFileDir, (errData: BusinessError) => {
        this.show = true;
        if (errData !== null) {
          console.error(`decompressFile failed. code is ${errData.code}, message is ${errData.message}`);
        }
      })
    } catch (errData) {
      let code = (errData as BusinessError).code;
      let message = (errData as BusinessError).message;
      console.error(`decompressFile failed. code is ${code}, message is ${message}`);
    }
  }

  myRawfileCopy(context: common.UIAbilityContext) {
    context.resourceManager.getRawFileContent("dist.zip", (err: BusinessError, data: Uint8Array) => {
      if (err != null) {
        console.error(`open aaa.txt failed: ${err.message}`)
      } else {
        let buffer = data.buffer
        let sanboxPath = context.filesDir
        console.log('myRawfileCopy path' + sanboxPath)
      }
    })
  }

  aboutToAppear() {
    webview.WebviewController.setWebDebuggingAccess(true);
  }

  build() {
    Column() {
      Text('复制文件到沙盒').onClick(() => {
        getContext(this).resourceManager.getRawFd('dist.zip').then(file => {
          this.copy2file(file as RawFileDescriptor)
        }).catch(err => {
          console.log(JSON.stringify(err));
        })
      })
      Text('解压').onClick(() => {
        this.testUnCompressZip();
      })
      if (this.show) {
        Web({ src: 'https://www.example.com/dist/index.html', controller: this.controller })
          .onInterceptRequest((event) => {
            if (!event) {
              return;
            }
            console.log(event.request.getRequestUrl())
            if (this.schemeMapSha.has(event.request.getRequestUrl())) {
              let shaFileName: string = this.schemeMapSha.get(event.request.getRequestUrl())!;
              let mimeType = this.mimeTypeMapSha.get(shaFileName);
              let response = new WebResourceResponse();
              if (typeof mimeType === 'string') {
                let data: string | ArrayBuffer = '';
                if (mimeType.includes('javascript') || mimeType.includes('css') || mimeType.includes('html')) {
                  data = fileIo.readTextSync(this.filesDir + '/' + shaFileName);
                }
                if (mimeType.includes('image') || mimeType.includes('mp4')) {
                  let file = fs.openSync(`${getContext().filesDir}/${shaFileName}`)
                  let stat = fs.statSync(file.fd)
                  let buf = new ArrayBuffer(stat.size)
                  fs.readSync(file.fd, buf)
                  data = buf;
                  fs.closeSync(file)
                }
                response.setResponseData(data);
                response.setResponseEncoding('utf-8');
                response.setResponseMimeType(mimeType);
                response.setResponseCode(200);
                response.setReasonMessage('OK');
                response.setResponseIsReady(true);
                return response;
              }
            }
            return null;
          })
          .onPageEnd(() => {
            // this.controller.runJavaScript('window.location.hash = "about/aboutchild"');
          })
      }
    }
    .height('100%')
    .width('100%')
  }
}

更多关于HarmonyOS 鸿蒙Next web加载应用沙盒.filesDir+"/JYLocalH5/"下的Vue打包文件,在onInterceptRequest做了映射后白屏,怎么解决?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


针对HarmonyOS鸿蒙系统中Next web加载应用沙盒/filesDir+"/JYLocalH5/"下的Vue打包文件,在onInterceptRequest做了映射后出现白屏的问题,可以尝试以下解决方案:

  1. 检查文件路径:确保/filesDir+"/JYLocalH5/"路径下的Vue打包文件完整且未损坏。可以通过文件管理器查看该路径下的文件,确认文件是否存在且大小正常。

  2. 验证映射配置:仔细检查onInterceptRequest中的映射配置,确保请求的URL正确映射到了对应的文件路径。确认映射规则无误,且请求的URL与映射规则匹配。

  3. 检查权限设置:确保应用具有访问沙盒内文件的权限。在鸿蒙系统中,应用沙盒内的文件访问受到严格限制,需要确认应用已正确申请并获得了必要的文件访问权限。

  4. 调试和日志:使用鸿蒙系统的开发者工具进行调试,查看加载过程中的日志输出,检查是否有错误信息或警告提示,根据日志信息定位问题。

  5. 清除缓存和数据:尝试清除应用的缓存和数据,然后重新启动应用,看是否能解决问题。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部