W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
Web組件支持在應(yīng)用攔截到頁面請求后自定義響應(yīng)請求能力。開發(fā)者通過onInterceptRequest()接口來實現(xiàn)自定義資源請求響應(yīng) 。自定義請求能力可以用于開發(fā)者自定義Web頁面響應(yīng)、自定義文件資源響應(yīng)等場景。
Web網(wǎng)頁上發(fā)起資源加載請求,應(yīng)用層收到資源請求消息。應(yīng)用層構(gòu)造本地資源響應(yīng)消息發(fā)送給Web內(nèi)核。Web內(nèi)核解析應(yīng)用層響應(yīng)信息,根據(jù)此響應(yīng)信息進行頁面資源加載。
在下面的示例中,Web組件通過攔截頁面請求“https://www.example.com/test.html”,在應(yīng)用側(cè)代碼構(gòu)建響應(yīng)資源,實現(xiàn)自定義頁面響應(yīng)場景。
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>example</title>
- </head>
- <body>
- <!-- 頁面資源請求 -->
- <a href="https://www.example.com/test.html">intercept test!</a>
- </body>
- </html>
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: web_webview.WebviewController = new web_webview.WebviewController()
- responseResource: WebResourceResponse = new WebResourceResponse()
- // 開發(fā)者自定義響應(yīng)數(shù)據(jù)
- @State webdata: string = "<!DOCTYPE html>\n" +
- "<html>\n"+
- "<head>\n"+
- "<title>intercept test</title>\n"+
- "</head>\n"+
- "<body>\n"+
- "<h1>intercept test</h1>\n"+
- "</body>\n"+
- "</html>"
- build() {
- Column() {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .onInterceptRequest((event?: Record<string, WebResourceRequest>): WebResourceResponse => {
- if (!event) {
- return new WebResourceResponse();
- }
- let mRequest: WebResourceRequest = event.request as WebResourceRequest;
- console.info('TAGLee: url:'+ mRequest.getRequestUrl());
- //攔截頁面請求,如果加載的url判斷與目標(biāo)url一致則返回自定義加載結(jié)果webdata
- if(mRequest.getRequestUrl() === 'https://www.example.com/test.html'){
- // 構(gòu)造響應(yīng)數(shù)據(jù)
- 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;
- }
- return;
- })
- }
- }
- }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: