1# 使用Web组件加载页面 2<!--Kit: ArkWeb--> 3<!--Subsystem: Web--> 4<!--Owner: @aohui--> 5<!--Designer: @yaomingliu--> 6<!--Tester: @ghiker--> 7<!--Adviser: @HelloCrease--> 8 9 10页面加载是Web组件的基本功能。根据页面加载数据来源可以分为三种常用场景,包括加载网络页面、加载本地页面、加载HTML格式的富文本数据。 11 12 13页面加载过程中,若涉及网络资源获取,请在module.json5中配置网络访问权限,添加方法请参考[在配置文件中声明权限](../security/AccessToken/declare-permissions.md#在配置文件中声明权限)。 14 15 ``` 16 "requestPermissions":[ 17 { 18 "name" : "ohos.permission.INTERNET" 19 } 20 ] 21 ``` 22 23## 加载网络页面 24 25开发者可以在Web组件创建时,指定默认加载的网络页面。在默认页面加载完成后,如果需要变更此Web组件显示的网络页面,可以通过调用[loadUrl()](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#loadurl)接口加载指定的网页。[Web组件](../reference/apis-arkweb/arkts-basic-components-web.md)的第一个参数变量src不能通过状态变量(例如:@State)动态更改地址,如需更改,请通过[loadUrl()](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#loadurl)重新加载。 26 27 28在下面的示例中,在Web组件加载完“www\.example.com”页面后,开发者可通过loadUrl接口将此Web组件显示页面变更为“www\.example1.com”。 29 30 31 32```ts 33// xxx.ets 34import { webview } from '@kit.ArkWeb'; 35import { BusinessError } from '@kit.BasicServicesKit'; 36 37@Entry 38@Component 39struct WebComponent { 40 controller: webview.WebviewController = new webview.WebviewController(); 41 42 build() { 43 Column() { 44 Button('loadUrl') 45 .onClick(() => { 46 try { 47 // 点击按钮时,通过loadUrl,跳转到www.example1.com 48 this.controller.loadUrl('www.example1.com'); 49 } catch (error) { 50 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 51 } 52 }) 53 // 组件创建时,加载www.example.com 54 Web({ src: 'www.example.com', controller: this.controller }) 55 } 56 } 57} 58``` 59 60 61## 加载本地页面 62 63为了在启动、跳转、弱网等场景下减少用户等待感知,同时为动态内容加载争取时间,可以加载本地页面优化用户体验。 64 65在下面的示例中展示加载本地页面文件的方法: 66 67将本地页面文件放在应用的rawfile目录下,开发者可以在Web组件创建的时候指定默认加载的本地页面,并且加载完成后可通过调用[loadUrl()](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#loadurl)接口变更当前Web组件的页面。 68 69加载本地html文件时引用本地css样式文件可以通过以下方法实现。 70 71```html 72<link rel="stylesheet" href="resource://rawfile/xxx.css"> 73<link rel="stylesheet" href="file:///data/storage/el2/base/haps/entry/cache/xxx.css">// 加载沙箱路径下的本地css文件。 74``` 75 76- 将资源文件放置在应用的resources/rawfile目录下。 77 78 **图1** 资源文件路径 79 80  81 82 83- 应用侧代码。 84 85 ```ts 86 // xxx.ets 87 import { webview } from '@kit.ArkWeb'; 88 import { BusinessError } from '@kit.BasicServicesKit'; 89 90 @Entry 91 @Component 92 struct WebComponent { 93 controller: webview.WebviewController = new webview.WebviewController(); 94 95 build() { 96 Column() { 97 Button('loadUrl') 98 .onClick(() => { 99 try { 100 // 点击按钮时,通过loadUrl,跳转到local1.html 101 this.controller.loadUrl($rawfile("local1.html")); 102 } catch (error) { 103 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 104 } 105 }) 106 // 组件创建时,通过$rawfile加载本地文件local.html 107 Web({ src: $rawfile("local.html"), controller: this.controller }) 108 } 109 } 110 } 111 ``` 112 113 114- local.html页面代码。 115 116 ```html 117 <!-- local.html --> 118 <!DOCTYPE html> 119 <html> 120 <body> 121 <p>Hello World</p> 122 </body> 123 </html> 124 ``` 125 126- local1.html页面代码。 127 128 ```html 129 <!-- local1.html --> 130 <!DOCTYPE html> 131 <html> 132 <body> 133 <p>This is local1 page</p> 134 </body> 135 </html> 136 ``` 137 138加载沙箱路径下的本地页面文件。 139 1401. 通过构造的单例对象GlobalContext获取沙箱路径。需要开启应用中文件系统的访问[fileAccess](../reference/apis-arkweb/arkts-basic-components-web-attributes.md#fileaccess)权限。 141 142 ```ts 143 // GlobalContext.ets 144 export class GlobalContext { 145 private constructor() {} 146 private static instance: GlobalContext; 147 private _objects = new Map<string, Object>(); 148 149 public static getContext(): GlobalContext { 150 if (!GlobalContext.instance) { 151 GlobalContext.instance = new GlobalContext(); 152 } 153 return GlobalContext.instance; 154 } 155 156 getObject(value: string): Object | undefined { 157 return this._objects.get(value); 158 } 159 160 setObject(key: string, objectClass: Object): void { 161 this._objects.set(key, objectClass); 162 } 163 } 164 ``` 165 166 ```ts 167 // xxx.ets 168 import { webview } from '@kit.ArkWeb'; 169 import { GlobalContext } from '../GlobalContext'; 170 171 let url = 'file://' + GlobalContext.getContext().getObject("filesDir") + '/index.html'; 172 173 @Entry 174 @Component 175 struct WebComponent { 176 controller: webview.WebviewController = new webview.WebviewController(); 177 178 build() { 179 Column() { 180 // 加载沙箱路径文件。 181 Web({ src: url, controller: this.controller }) 182 .fileAccess(true) 183 } 184 } 185 } 186 ``` 187 1882. 修改`EntryAbility.ets`文件。 189 190 以filesDir为例,获取沙箱路径。若想获取其他路径,请参考[应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 191 192 ```ts 193 // xxx.ets 194 import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 195 import { webview } from '@kit.ArkWeb'; 196 import { GlobalContext } from '../GlobalContext'; 197 198 export default class EntryAbility extends UIAbility { 199 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 200 // 通过在GlobalContext对象上绑定filesDir,可以实现UIAbility组件与UI之间的数据同步。 201 GlobalContext.getContext().setObject("filesDir", this.context.filesDir); 202 console.log("Sandbox path is " + GlobalContext.getContext().getObject("filesDir")); 203 } 204 } 205 ``` 206 207 加载的html文件。 208 209 ```html 210 <!-- index.html --> 211 <!DOCTYPE html> 212 <html> 213 <body> 214 <p>Hello World</p> 215 </body> 216 </html> 217 ``` 218 219 220## 加载HTML格式的文本数据 221 222Web组件可以通过[loadData()](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#loaddata)接口实现加载HTML格式的文本数据。当开发者不需要加载整个页面,只需要显示一些页面片段时,可通过此功能来快速加载页面,当加载大量html文件时,需设置第四个参数baseUrl为"data"。 223 224```ts 225// xxx.ets 226import { webview } from '@kit.ArkWeb'; 227import { BusinessError } from '@kit.BasicServicesKit'; 228 229@Entry 230@Component 231struct WebComponent { 232 controller: webview.WebviewController = new webview.WebviewController(); 233 234 build() { 235 Column() { 236 Button('loadData') 237 .onClick(() => { 238 try { 239 // 点击按钮时,通过loadData,加载HTML格式的文本数据 240 this.controller.loadData( 241 "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>", 242 "text/html", 243 "UTF-8" 244 ); 245 } catch (error) { 246 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 247 } 248 }) 249 // 组件创建时,加载www.example.com 250 Web({ src: 'www.example.com', controller: this.controller }) 251 } 252 } 253} 254``` 255 256Web组件可以通过data url方式直接加载HTML字符串。 257 258```ts 259// xxx.ets 260import { webview } from '@kit.ArkWeb'; 261import { BusinessError } from '@kit.BasicServicesKit'; 262 263@Entry 264@Component 265struct WebComponent { 266 controller: webview.WebviewController = new webview.WebviewController(); 267 htmlStr: string = "data:text/html, <html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>"; 268 269 build() { 270 Column() { 271 // 组件创建时,加载htmlStr 272 Web({ src: this.htmlStr, controller: this.controller }) 273 } 274 } 275} 276``` 277 278## resource协议加载本地资源 279 280resource协议允许访问应用资源目录中的文件。 281 282```ts 283import { webview } from '@kit.ArkWeb'; 284 285@Entry 286@Component 287struct ResourceWebComponent { 288 controller: webview.WebviewController = new webview.WebviewController(); 289 290 build() { 291 Column() { 292 Button('加载Resource资源') 293 .onClick(() => { 294 try { 295 // 通过resource加载resources/rawfile目录下的index1.html文件 296 this.controller.loadUrl('resource://rawfile/index1.html'); 297 } catch (error) { 298 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 299 } 300 }) 301 302 // 组件创建时直接使用resource协议加载资源 303 Web({ 304 src: 'resource://rawfile/index.html', controller: this.controller}) 305 } 306 } 307} 308``` 309 310在“src\main\resources\rawfile”文件夹下创建index.html: 311```html 312<!-- index.html --> 313<!DOCTYPE html> 314<html> 315 <body> 316 <p>Hello World</p> 317 </body> 318</html> 319``` 320 321在“src\main\resources\rawfile”文件夹下创建index1.html: 322 323```html 324<!-- index1.html --> 325<!DOCTYPE html> 326<html> 327 <body> 328 <p>Hello World Again</p> 329 </body> 330</html> 331``` 332 333## 相关实例 334 335针对Web组件开发,有以下相关实例可供参考: 336 337- [浏览器(ArkTS)(Full SDK)(API9)](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Web/Browser) 338