• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Loading Pages by Using the Web Component
2
3
4Page loading is a basic function of the **Web** component. Depending on the data source, page loading falls into three types: loading of network pages, loading of local pages, and loading of HTML rich text data.
5
6
7If acquisition of network resources is involved in page loading, you need to declare the [ohos.permission.INTERNET](../security/AccessToken/declare-permissions.md) permission.
8
9
10## Loading Network Pages
11
12You can specify the default network page to be loaded when creating a **Web** component. After the default network page is loaded, call [loadUrl()](../reference/apis-arkweb/js-apis-webview.md#loadurl) if you want to change the network page displayed by the **Web** component.
13
14
15In the following example, after the **www.\example.com** page is loaded by the **Web** component, **loadUrl** is called to change the displayed page to **www\.example1.com**.
16
17
18
19```ts
20// xxx.ets
21import web_webview from '@ohos.web.webview';
22import business_error from '@ohos.base';
23
24@Entry
25@Component
26struct WebComponent {
27  webviewController: web_webview.WebviewController = new web_webview.WebviewController();
28
29  build() {
30    Column() {
31      Button('loadUrl')
32        .onClick(() => {
33          try {
34            // Upon button clicking, call loadUrl to redirect to www.example1.com.
35            this.webviewController.loadUrl('www.example1.com');
36          } catch (error) {
37            let e: business_error.BusinessError = error as business_error.BusinessError;
38            console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
39          }
40        })
41      // When creating a Web component, set the default network page to be loaded to www.example.com.
42      Web({ src: 'www.example.com', controller: this.webviewController})
43    }
44  }
45}
46```
47
48
49## Loading Local Pages
50
51Local page files are stored in the application's **rawfile** directory. You can specify the local page to be loaded by default when creating a **Web** component. After page loading is complete, you can call [loadUrl()](../reference/apis-arkweb/js-apis-webview.md#loadurl) to change the displayed page of the **Web** component.
52
53
54The following example shows how to load a local page file.
55
56
57- Local page file in the application's resources/rawfile directory:
58
59    **Figure 1** Path of local page files
60
61    ![resource-path](figures/resource-path.png)
62
63
64- Application code:
65
66  ```ts
67  // xxx.ets
68  import web_webview from '@ohos.web.webview';
69  import business_error from '@ohos.base';
70
71  @Entry
72  @Component
73  struct WebComponent {
74    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
75
76    build() {
77      Column() {
78        Button('loadUrl')
79          .onClick(() => {
80            try {
81              // Upon button clicking, call loadUrl to redirect to local1.html.
82              this.webviewController.loadUrl($rawfile("local1.html"));
83            } catch (error) {
84              let e: business_error.BusinessError = error as business_error.BusinessError;
85              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
86            }
87          })
88        // When creating a Web component, load the local.html file through $rawfile.
89        Web({ src: $rawfile("local.html"), controller: this.webviewController })
90      }
91    }
92  }
93  ```
94
95
96- Code of the **local.html** page:
97
98  ```html
99  <!-- local.html -->
100  <!DOCTYPE html>
101  <html>
102    <body>
103      <p>Hello World</p>
104    </body>
105  </html>
106  ```
107
108
109## Loading HTML Rich Text Data
110
111The **Web** component provides the [loadData()](../reference/apis-arkweb/js-apis-webview.md#loaddata) API for you to load HTML rich text data. This API is applicable if you want to display some page sections instead of the entire page.
112
113
114
115```ts
116// xxx.ets
117import web_webview from '@ohos.web.webview';
118import business_error from '@ohos.base';
119
120@Entry
121@Component
122struct WebComponent {
123  controller: web_webview.WebviewController = new web_webview.WebviewController();
124
125  build() {
126    Column() {
127      Button('loadData')
128        .onClick(() => {
129          try {
130            // Upon button clicking, call loadData to load HTML rich text data.
131            this.controller.loadData(
132              "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>",
133              "text/html",
134              "UTF-8"
135            );
136          } catch (error) {
137            let e: business_error.BusinessError = error as business_error.BusinessError;
138            console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
139          }
140        })
141      // When creating a Web component, set the default network page to be loaded to www.example.com.
142      Web({ src: 'www.example.com', controller: this.controller })
143    }
144  }
145}
146```
147
148## Dynamically Creating Web Components
149**Web** components can be created with commands. Components created in this mode are not immediately mounted to the component tree, that is, they are not presented to users (their state is **Hidden** or **InActive**). You can dynamically mount the components as required in subsequent use. It is recommended that the number of **Web** instances started in the background be less than or equal to 200.
150
151```ts
152// Carrier ability
153// EntryAbility.ets
154import {createNWeb} from "../pages/common"
155onWindowStageCreate(windowStage: window.WindowStage): void {
156  windowStage.loadContent('pages/Index', (err, data) => {
157    // Dynamically create a Web component (UIContext needs to be passed in). The component can be created at any time after loadContent is called.
158    createNWeb("https://www.example.com", windowStage.getMainWindowSync().getUIContext());
159    if (err.code) {
160      return;
161    }
162  });
163}
164```
165```ts
166// Create a NodeController instance.
167// common.ets
168import { UIContext } from '@ohos.arkui.UIContext';
169import web_webview from '@ohos.web.webview'
170import { NodeController, BuilderNode, Size, FrameNode }  from '@ohos.arkui.node';
171// @Builder contains the specific content of the dynamically created component.
172// Data is the class for input parameter encapsulation.
173class Data{
174  url: string = "https://www.example.com";
175  controller: WebviewController = new web_webview.WebviewController();
176}
177
178@Builder
179function WebBuilder(data:Data) {
180  Column() {
181    Web({ src: data.url, controller: data.controller })
182      .width("100%")
183      .height("100%")
184  }
185}
186
187let wrap = wrapBuilder<Data[]>(WebBuilder);
188
189// NodeController is used to control and feed back the behavior of the corresponding node in the NodeContainer. It must be used together with NodeContainer.
190export class myNodeController extends NodeController {
191  private rootnode: BuilderNode<Data[]> | null = null;
192  // This method must be overridden. It is used to construct the number of nodes and return the number of nodes mounted to the corresponding NodeContainer.
193  // Called when the corresponding NodeContainer is created or called through the rebuild method.
194  makeNode(uiContext: UIContext): FrameNode | null {
195    console.log(" uicontext is undifined : "+ (uiContext === undefined));
196    if (this.rootnode != null) {
197      // Return the FrameNode.
198      return this.rootnode.getFrameNode();
199    }
200    // Return null to control the dynamic component to be detached from the bound node.
201    return null;
202  }
203  // Called when the layout size changes.
204  aboutToResize(size: Size) {
205    console.log("aboutToResize width : " + size.width  +  " height : " + size.height )
206  }
207
208  // Called when the NodeContainer bound to the current controller is about to be displayed.
209  aboutToAppear() {
210    console.log("aboutToAppear")
211  }
212
213  // Called when the NodeContainer bound to the current controller is about to be hidden.
214  aboutToDisappear() {
215    console.log("aboutToDisappear")
216  }
217
218  // This function is a custom function and can be used as an initialization function.
219  // Initialize BuilderNode through UIContext, and then initialize the content in @Builder through the build API in BuilderNode.
220  initWeb(url:string, uiContext:UIContext, control:WebviewController) {
221    if(this.rootnode != null)
222    {
223      return;
224    }
225    // Create a node. uiContext is required.
226    this.rootnode = new BuilderNode(uiContext)
227    // Create a dynamic Web component.
228    this.rootnode.build(wrap, { url:url, controller:control })
229  }
230}
231 // Create a map to save the required NodeController.
232let NodeMap:Map<string, myNodeController | undefined> = new Map();
233// Create a map to save the required WebViewController.
234let controllerMap:Map<string, WebviewController | undefined> = new Map();
235
236// UIContext is required for initialization and needs to be obtained from the ability.
237export const createNWeb = (url: string, uiContext: UIContext) => {
238  // Create a NodeController.
239  let baseNode = new myNodeController();
240  let controller = new web_webview.WebviewController() ;
241  // Initialize the custom Web component.
242  baseNode.initWeb(url, uiContext, controller);
243  controllerMap.set(url, controller)
244  NodeMap.set(url, baseNode);
245}
246// Customize the API for obtaining the NodeController.
247export const getNWeb = (url : string) : myNodeController | undefined => {
248  return NodeMap.get(url);
249}
250```
251```ts
252// Use the Page page of the NodeController.
253// Index.ets
254import {createNWeb, getNWeb} from "./common"
255@Entry
256@Component
257struct Index {
258  build() {
259    Row() {
260      Column() {
261        // NodeContainer is used to bind to the NodeController. A rebuild call triggers makeNode.
262        // The Page page is bound to the NodeController through the NodeContainer API to display the dynamic component.
263        NodeContainer(getNWeb("https://www.example.com"))
264          .height("90%")
265          .width("100%")
266      }
267      .width('100%')
268    }
269    .height('100%')
270  }
271}
272
273```
274