自定義頁面請求響應

2024-02-16 13:41 更新

Web組件支持在應用攔截到頁面請求后自定義響應請求能力。開發(fā)者通過onInterceptRequest()接口來實現(xiàn)自定義資源請求響應 。自定義請求能力可以用于開發(fā)者自定義Web頁面響應、自定義文件資源響應等場景。

Web網頁上發(fā)起資源加載請求,應用層收到資源請求消息。應用層構造本地資源響應消息發(fā)送給Web內核。Web內核解析應用層響應信息,根據此響應信息進行頁面資源加載。

在下面的示例中,Web組件通過攔截頁面請求“https://www.example.com/test.html”,在應用側代碼構建響應資源,實現(xiàn)自定義頁面響應場景。

  • 前端頁面index.html代碼。
    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <meta charset="utf-8">
    5. <title>example</title>
    6. </head>
    7. <body>
    8. <!-- 頁面資源請求 -->
    9. <a href="https://www.example.com/test.html">intercept test!</a>
    10. </body>
    11. </html>
  • 應用側代碼。
    1. // xxx.ets
    2. import web_webview from '@ohos.web.webview'
    3. @Entry
    4. @Component
    5. struct WebComponent {
    6. controller: web_webview.WebviewController = new web_webview.WebviewController()
    7. responseResource: WebResourceResponse = new WebResourceResponse()
    8. // 開發(fā)者自定義響應數(shù)據
    9. @State webdata: string = "<!DOCTYPE html>\n" +
    10. "<html>\n"+
    11. "<head>\n"+
    12. "<title>intercept test</title>\n"+
    13. "</head>\n"+
    14. "<body>\n"+
    15. "<h1>intercept test</h1>\n"+
    16. "</body>\n"+
    17. "</html>"
    18. build() {
    19. Column() {
    20. Web({ src: $rawfile('index.html'), controller: this.controller })
    21. .onInterceptRequest((event?: Record<string, WebResourceRequest>): WebResourceResponse => {
    22. if (!event) {
    23. return new WebResourceResponse();
    24. }
    25. let mRequest: WebResourceRequest = event.request as WebResourceRequest;
    26. console.info('TAGLee: url:'+ mRequest.getRequestUrl());
    27. //攔截頁面請求,如果加載的url判斷與目標url一致則返回自定義加載結果webdata
    28. if(mRequest.getRequestUrl() === 'https://www.example.com/test.html'){
    29. // 構造響應數(shù)據
    30. this.responseResource.setResponseData(this.webdata);
    31. this.responseResource.setResponseEncoding('utf-8');
    32. this.responseResource.setResponseMimeType('text/html');
    33. this.responseResource.setResponseCode(200);
    34. this.responseResource.setReasonMessage('OK');
    35. return this.responseResource;
    36. }
    37. return;
    38. })
    39. }
    40. }
    41. }
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號