1# 自定义页面请求响应 2 3 4Web组件支持在应用拦截到页面请求后自定义响应请求能力。开发者通过[onInterceptRequest()](../reference/arkui-ts/ts-basic-components-web.md#oninterceptrequest9)接口来实现自定义资源请求响应 。自定义请求能力可以用于开发者自定义Web页面响应、自定义文件资源响应等场景。 5 6 7Web网页上发起资源加载请求,应用层收到资源请求消息。应用层构造本地资源响应消息发送给Web内核。Web内核解析应用层响应信息,根据此响应信息进行页面资源加载。 8 9 10在下面的示例中,Web组件通过拦截页面请求“https://www.example.com/test.html”, 在应用侧代码构建响应资源,实现自定义页面响应场景。 11 12 13- 前端页面index.html代码。 14 15 ```html 16 <!DOCTYPE html> 17 <html> 18 <head> 19 <meta charset="utf-8"> 20 </head> 21 <body> 22 <!-- 页面资源请求 --> 23 <a href="https://www.example.com/test.html">intercept test!</a> 24 </body> 25 </html> 26 ``` 27 28- 应用侧代码。 29 30 ```ts 31 // xxx.ets 32 import web_webview from '@ohos.web.webview'; 33 34 @Entry 35 @Component 36 struct WebComponent { 37 controller: web_webview.WebviewController = new web_webview.WebviewController() 38 responseResource: WebResourceResponse = new WebResourceResponse() 39 // 开发者自定义响应数据 40 @State webData: string = '<!DOCTYPE html>\n' + 41 '<html>\n'+ 42 '<head>\n'+ 43 '<title>intercept test</title>\n'+ 44 '</head>\n'+ 45 '<body>\n'+ 46 '<h1>intercept ok</h1>\n'+ 47 '</body>\n'+ 48 '</html>' 49 build() { 50 Column() { 51 Web({ src: $rawfile('index.html'), controller: this.controller }) 52 .onInterceptRequest((event) => { 53 if (event) { 54 console.info('url:' + event.request.getRequestUrl()); 55 // 拦截页面请求 56 if (event.request.getRequestUrl() !== 'https://www.example.com/test.html') { 57 return null; 58 } 59 } 60 // 构造响应数据 61 this.responseResource.setResponseData(this.webData); 62 this.responseResource.setResponseEncoding('utf-8'); 63 this.responseResource.setResponseMimeType('text/html'); 64 this.responseResource.setResponseCode(200); 65 this.responseResource.setReasonMessage('OK'); 66 return this.responseResource; 67 }) 68 } 69 } 70 } 71 ``` 72