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