• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.router (Page Routing)
2
3The **Router** module provides APIs to access pages through URLs. You can use the APIs to navigate to a specified page in an application, replace the current page with another one in an application, and return to the previous page or a specified page.
4
5> **NOTE**
6>
7> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>
9> - Page routing APIs can be invoked only after page rendering is complete. Do not call these APIs in **onInit** and **onReady** when the page is still in the rendering phase.
10
11## Modules to Import
12
13```
14import router from '@ohos.router'
15```
16
17## router.pushUrl<sup>9+</sup>
18
19pushUrl(options: RouterOptions): Promise&lt;void&gt;
20
21Navigates to a specified page in the application.
22
23**System capability**: SystemCapability.ArkUI.ArkUI.Full
24
25**Parameters**
26
27| Name    | Type                             | Mandatory  | Description       |
28| ------- | ------------------------------- | ---- | --------- |
29| options | [RouterOptions](#routeroptions) | Yes   | Page routing parameters.|
30
31**Return value**
32
33| Type               | Description       |
34| ------------------- | --------- |
35| Promise&lt;void&gt; | Promise used to return the result.|
36
37**Error codes**
38
39For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
40
41| ID  | Error Message|
42| --------- | ------- |
43| 100001    | if UI execution context not found. |
44| 100002    | if the uri is not exist. |
45| 100003    | if the pages are pushed too much. |
46
47**Example**
48
49```js
50router.pushUrl({
51  url: 'pages/routerpage2',
52  params: {
53    data1: 'message',
54    data2: {
55      data3: [123, 456, 789]
56    }
57  }
58})
59  .then(() => {
60    // success
61  })
62  .catch(err => {
63    console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
64  })
65```
66
67## router.pushUrl<sup>9+</sup>
68
69pushUrl(options: RouterOptions, callback: AsyncCallback&lt;void&gt;): void
70
71Navigates to a specified page in the application.
72
73**System capability**: SystemCapability.ArkUI.ArkUI.Full
74
75**Parameters**
76
77| Name    | Type                             | Mandatory  | Description       |
78| ------- | ------------------------------- | ---- | --------- |
79| options | [RouterOptions](#routeroptions) | Yes   | Page routing parameters.|
80| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |
81
82**Error codes**
83
84For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
85
86| ID  | Error Message|
87| --------- | ------- |
88| 100001    | if UI execution context not found. |
89| 100002    | if the uri is not exist. |
90| 100003    | if the pages are pushed too much. |
91
92**Example**
93
94```js
95router.pushUrl({
96  url: 'pages/routerpage2',
97  params: {
98    data1: 'message',
99    data2: {
100      data3: [123, 456, 789]
101    }
102  }
103}, (err) => {
104  if (err) {
105    console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
106    return;
107  }
108  console.info('pushUrl success');
109});
110```
111## router.pushUrl<sup>9+</sup>
112
113pushUrl(options: RouterOptions, mode: RouterMode): Promise&lt;void&gt;
114
115Navigates to a specified page in the application.
116
117**System capability**: SystemCapability.ArkUI.ArkUI.Full
118
119**Parameters**
120
121| Name    | Type                             | Mandatory  | Description        |
122| ------- | ------------------------------- | ---- | ---------- |
123| options | [RouterOptions](#routeroptions) | Yes   | Page routing parameters. |
124| mode    | [RouterMode](#routermode9)      | Yes   | Routing mode.|
125
126**Return value**
127
128| Type               | Description       |
129| ------------------- | --------- |
130| Promise&lt;void&gt; | Promise used to return the result.|
131
132**Error codes**
133
134For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
135
136| ID  | Error Message|
137| --------- | ------- |
138| 100001    | if UI execution context not found. |
139| 100002    | if the uri is not exist. |
140| 100003    | if the pages are pushed too much. |
141
142**Example**
143
144```js
145router.pushUrl({
146  url: 'pages/routerpage2',
147  params: {
148    data1: 'message',
149    data2: {
150      data3: [123, 456, 789]
151    }
152  }
153}, router.RouterMode.Standard)
154  .then(() => {
155    // success
156  })
157  .catch(err => {
158    console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
159  })
160```
161
162## router.pushUrl<sup>9+</sup>
163
164pushUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback&lt;void&gt;): void
165
166Navigates to a specified page in the application.
167
168**System capability**: SystemCapability.ArkUI.ArkUI.Full
169
170**Parameters**
171
172| Name    | Type                             | Mandatory  | Description        |
173| ------- | ------------------------------- | ---- | ---------- |
174| options | [RouterOptions](#routeroptions) | Yes   | Page routing parameters. |
175| mode    | [RouterMode](#routermode9)      | Yes   | Routing mode.|
176| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |
177
178**Error codes**
179
180For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
181
182| ID  | Error Message|
183| --------- | ------- |
184| 100001    | if UI execution context not found. |
185| 100002    | if the uri is not exist. |
186| 100003    | if the pages are pushed too much. |
187
188**Example**
189
190```js
191router.pushUrl({
192  url: 'pages/routerpage2',
193  params: {
194    data1: 'message',
195    data2: {
196      data3: [123, 456, 789]
197    }
198  }
199}, router.RouterMode.Standard, (err) => {
200  if (err) {
201    console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
202    return;
203  }
204  console.info('pushUrl success');
205});
206```
207
208## router.replaceUrl<sup>9+</sup>
209
210replaceUrl(options: RouterOptions): Promise&lt;void&gt;
211
212Replaces the current page with another one in the application and destroys the current page.
213
214**System capability**: SystemCapability.ArkUI.ArkUI.Lite
215
216**Parameters**
217
218| Name | Type                           | Mandatory| Description              |
219| ------- | ------------------------------- | ---- | ------------------ |
220| options | [RouterOptions](#routeroptions) | Yes  | Description of the new page.|
221
222**Return value**
223
224| Type               | Description       |
225| ------------------- | --------- |
226| Promise&lt;void&gt; | Promise used to return the result.|
227
228**Error codes**
229
230For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
231
232| ID  | Error Message|
233| --------- | ------- |
234| 100001    | if UI execution context not found, only throw in standard system. |
235| 200002    | if the uri is not exist. |
236
237**Example**
238
239```js
240router.replaceUrl({
241  url: 'pages/detail',
242  params: {
243    data1: 'message'
244  }
245})
246  .then(() => {
247    // success
248  })
249  .catch(err => {
250    console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
251  })
252```
253
254## router.replaceUrl<sup>9+</sup>
255
256replaceUrl(options: RouterOptions, callback: AsyncCallback&lt;void&gt;): void
257
258Replaces the current page with another one in the application and destroys the current page.
259
260**System capability**: SystemCapability.ArkUI.ArkUI.Lite
261
262**Parameters**
263
264| Name | Type                           | Mandatory| Description              |
265| ------- | ------------------------------- | ---- | ------------------ |
266| options | [RouterOptions](#routeroptions) | Yes  | Description of the new page.|
267| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |
268
269**Error codes**
270
271For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
272
273| ID  | Error Message|
274| --------- | ------- |
275| 100001    | if UI execution context not found, only throw in standard system. |
276| 200002    | if the uri is not exist. |
277
278**Example**
279
280```js
281router.replaceUrl({
282  url: 'pages/detail',
283  params: {
284    data1: 'message'
285  }
286}, (err) => {
287  if (err) {
288    console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
289    return;
290  }
291  console.info('replaceUrl success');
292});
293```
294
295## router.replaceUrl<sup>9+</sup>
296
297replaceUrl(options: RouterOptions, mode: RouterMode): Promise&lt;void&gt;
298
299Replaces the current page with another one in the application and destroys the current page.
300
301**System capability**: SystemCapability.ArkUI.ArkUI.Lite
302
303**Parameters**
304
305| Name    | Type                             | Mandatory  | Description        |
306| ------- | ------------------------------- | ---- | ---------- |
307| options | [RouterOptions](#routeroptions) | Yes   | Description of the new page. |
308| mode    | [RouterMode](#routermode9)      | Yes   | Routing mode.|
309
310
311**Return value**
312
313| Type               | Description       |
314| ------------------- | --------- |
315| Promise&lt;void&gt; | Promise used to return the result.|
316
317**Error codes**
318
319For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
320
321| ID  | Error Message|
322| --------- | ------- |
323| 100001    | if UI execution context not found, only throw in standard system. |
324| 200002    | if the uri is not exist. |
325
326**Example**
327
328```js
329router.replaceUrl({
330  url: 'pages/detail',
331  params: {
332    data1: 'message'
333  }
334}, router.RouterMode.Standard)
335  .then(() => {
336    // success
337  })
338  .catch(err => {
339    console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
340  })
341```
342
343## router.replaceUrl<sup>9+</sup>
344
345replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback&lt;void&gt;): void
346
347Replaces the current page with another one in the application and destroys the current page.
348
349**System capability**: SystemCapability.ArkUI.ArkUI.Lite
350
351**Parameters**
352
353| Name    | Type                             | Mandatory  | Description        |
354| ------- | ------------------------------- | ---- | ---------- |
355| options | [RouterOptions](#routeroptions) | Yes   | Description of the new page. |
356| mode    | [RouterMode](#routermode9)      | Yes   | Routing mode.|
357| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |
358
359**Error codes**
360
361For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
362
363| ID  | Error Message|
364| --------- | ------- |
365| 100001    | if can not get the delegate, only throw in standard system. |
366| 200002    | if the uri is not exist. |
367
368**Example**
369
370```js
371router.replaceUrl({
372  url: 'pages/detail',
373  params: {
374    data1: 'message'
375  }
376}, router.RouterMode.Standard, (err) => {
377  if (err) {
378    console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
379    return;
380  }
381  console.info('replaceUrl success');
382});
383
384```
385
386## router.back
387
388back(options?: RouterOptions ): void
389
390Returns to the previous page or a specified page.
391
392**System capability**: SystemCapability.ArkUI.ArkUI.Full
393
394**Parameters**
395
396| Name | Type                           | Mandatory| Description                                                        |
397| ------- | ------------------------------- | ---- | ------------------------------------------------------------ |
398| options | [RouterOptions](#routeroptions) | No  | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the application returns to the previous page, and the page is not rebuilt. The page in the page stack is not reclaimed. It will be reclaimed after being popped up.|
399
400**Example**
401
402```js
403router.back({url:'pages/detail'});
404```
405
406## router.clear
407
408clear(): void
409
410Clears all historical pages in the stack and retains only the current page at the top of the stack.
411
412**System capability**: SystemCapability.ArkUI.ArkUI.Full
413
414**Example**
415
416```js
417router.clear();
418```
419
420## router.getLength
421
422getLength(): string
423
424Obtains the number of pages in the current stack.
425
426**System capability**: SystemCapability.ArkUI.ArkUI.Full
427
428**Return value**
429
430| Type    | Description                |
431| ------ | ------------------ |
432| string | Number of pages in the stack. The maximum value is **32**.|
433
434**Example**
435
436```js
437let size = router.getLength();
438console.log('pages stack size = ' + size);
439```
440
441## router.getState
442
443getState(): RouterState
444
445Obtains state information about the current page.
446
447**System capability**: SystemCapability.ArkUI.ArkUI.Full
448
449**Return value**
450
451| Type                         | Description     |
452| --------------------------- | ------- |
453| [RouterState](#routerstate) | Page routing state.|
454
455**Example**
456
457```js
458let page = router.getState();
459console.log('current index = ' + page.index);
460console.log('current name = ' + page.name);
461console.log('current path = ' + page.path);
462```
463
464## RouterState
465
466Describes the page routing state.
467
468**System capability**: SystemCapability.ArkUI.ArkUI.Full
469
470| Name | Type  | Mandatory| Description                                                        |
471| ----- | ------ | ---- | ------------------------------------------------------------ |
472| index | number | Yes  | Index of the current page in the stack. The index starts from 1 from the bottom to the top of the stack.|
473| name  | string | No  | Name of the current page, that is, the file name.                          |
474| path  | string | Yes  | Path of the current page.                                        |
475
476## router.showAlertBeforeBackPage<sup>9+</sup>
477
478showAlertBeforeBackPage(options: EnableAlertOptions): void
479
480Enables the display of a confirm dialog box before returning to the previous page.
481
482**System capability**: SystemCapability.ArkUI.ArkUI.Full
483
484**Parameters**
485
486| Name    | Type                                      | Mandatory  | Description       |
487| ------- | ---------------------------------------- | ---- | --------- |
488| options | [EnableAlertOptions](#enablealertoptions) | Yes   | Description of the dialog box.|
489
490**Error codes**
491
492For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
493
494| ID  | Error Message|
495| --------- | ------- |
496| 100001    | if UI execution context not found. |
497
498**Example**
499
500  ```js
501try {
502  router.showAlertBeforeBackPage({
503    message: 'Message Info'
504  });
505} catch(error) {
506  console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`);
507}
508  ```
509## EnableAlertOptions
510
511Describes the confirm dialog box.
512
513**System capability**: SystemCapability.ArkUI.ArkUI.Full
514
515| Name     | Type    | Mandatory  | Description      |
516| ------- | ------ | ---- | -------- |
517| message | string | Yes   | Content displayed in the confirm dialog box.|
518
519## router.hideAlertBeforeBackPage<sup>9+</sup>
520
521hideAlertBeforeBackPage(): void
522
523Disables the display of a confirm dialog box before returning to the previous page.
524
525**System capability**: SystemCapability.ArkUI.ArkUI.Full
526
527**Example**
528
529```js
530router.hideAlertBeforeBackPage();
531```
532
533##  router.getParams
534
535getParams(): Object
536
537Obtains the parameters passed from the page that initiates redirection to the current page.
538
539**System capability**: SystemCapability.ArkUI.ArkUI.Full
540
541**Return value**
542
543| Type  | Description                              |
544| ------ | ---------------------------------- |
545| object | Parameters passed from the page that initiates redirection to the current page.|
546
547**Example**
548
549```
550router.getParams();
551```
552
553## RouterOptions
554
555Describes the page routing options.
556
557**System capability**: SystemCapability.ArkUI.ArkUI.Lite
558
559| Name  | Type  | Mandatory| Description                                                        |
560| ------ | ------ | ---- | ------------------------------------------------------------ |
561| url    | string | Yes  | URL of the target page, in either of the following formats:<br>- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:<br>- pages/index/index<br>- pages/detail/detail<br>- Particular path. If the URL is a slash (/), the home page is displayed.|
562| params | object | No  | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.|
563
564
565  > **NOTE**
566  >
567  > The page routing stack supports a maximum of 32 pages.
568
569## RouterMode<sup>9+</sup>
570
571Enumerates the routing modes.
572
573**System capability**: SystemCapability.ArkUI.ArkUI.Full
574
575| Name    | Description                                                        |
576| -------- | ------------------------------------------------------------ |
577| Standard | Multi-instance mode. It is the default routing mode.<br>The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.<br>**NOTE**<br>If the routing mode is not used, the page is redirected to in multi-instance mode.|
578| Single   | Singleton mode.<br>If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved to the top and becomes a new page.<br>If the URL of the target page does not exist in the page stack, the page is redirected to in multi-instance mode.|
579
580## Examples
581
582### JavaScript-based Web-like Development Paradigm
583
584```js
585// Current page
586export default {
587  pushPage() {
588    router.push({
589      url: 'pages/detail/detail',
590      params: {
591        data1: 'message'
592      }
593    });
594  }
595}
596```
597```js
598// detail page
599export default {
600  onInit() {
601    console.info('showData1:' + router.getParams()['data1']);
602  }
603}
604```
605
606### TypeScript-based Declarative Development Paradigm
607
608```ts
609// Navigate to the target page through router.pushUrl with the params parameter carried.
610import router from '@ohos.router'
611
612@Entry
613@Component
614struct Index {
615  async  routePage() {
616    let options = {
617      url: 'pages/second',
618      params: {
619        text: 'This is the value on the first page.',
620        data: {
621          array: [12, 45, 78]
622        }
623      }
624    }
625    try {
626      await router.pushUrl(options)
627    } catch (err) {
628      console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`)
629    }
630  }
631
632  build() {
633    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
634      Text('This is the first page.')
635        .fontSize(50)
636        .fontWeight(FontWeight.Bold)
637      Button() {
638        Text('next page')
639          .fontSize(25)
640          .fontWeight(FontWeight.Bold)
641      }.type(ButtonType.Capsule)
642      .margin({ top: 20 })
643      .backgroundColor('#ccc')
644      .onClick(() => {
645        this.routePage()
646      })
647    }
648    .width('100%')
649    .height('100%')
650  }
651}
652```
653
654```ts
655// Receive the transferred parameters on the second page.
656import router from '@ohos.router'
657
658@Entry
659@Component
660struct Second {
661  private content: string = "This is the second page."
662  @State text: string = router.getParams()['text']
663  @State data: object = router.getParams()['data']
664  @State secondData : string = ''
665
666  build() {
667    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
668      Text(`${this.content}`)
669        .fontSize(50)
670        .fontWeight(FontWeight.Bold)
671      Text(this.text)
672        .fontSize(30)
673        .onClick(()=>{
674          this.secondData = (this.data.['array'][1]).toString()
675        })
676      .margin({top:20})
677      Text(`This is the data passed from the first page: ${this.secondData}`)
678        .fontSize(20)
679        .margin({top:20})
680        .backgroundColor('red')
681    }
682    .width('100%')
683    .height('100%')
684  }
685}
686```
687
688## router.push<sup>(deprecated)</sup>
689
690push(options: RouterOptions): void
691
692Navigates to a specified page in the application.
693
694This API is deprecated since API version 9. You are advised to use [pushUrl<sup>9+</sup>](#routerpushurl9) instead.
695
696**System capability**: SystemCapability.ArkUI.ArkUI.Full
697
698**Parameters**
699
700| Name    | Type                             | Mandatory  | Description       |
701| ------- | ------------------------------- | ---- | --------- |
702| options | [RouterOptions](#routeroptions) | Yes   | Page routing parameters.|
703
704
705**Example**
706
707```js
708router.push({
709  url: 'pages/routerpage2',
710  params: {
711    data1: 'message',
712    data2: {
713      data3: [123, 456, 789]
714    }
715  }
716});
717```
718
719## router.replace<sup>(deprecated)</sup>
720
721replace(options: RouterOptions): void
722
723Replaces the current page with another one in the application and destroys the current page.
724
725This API is deprecated since API version 9. You are advised to use [replaceUrl<sup>9+</sup>](#routerreplaceurl9) instead.
726
727**System capability**: SystemCapability.ArkUI.ArkUI.Lite
728
729**Parameters**
730
731| Name | Type                           | Mandatory| Description              |
732| ------- | ------------------------------- | ---- | ------------------ |
733| options | [RouterOptions](#routeroptions) | Yes  | Description of the new page.|
734
735**Example**
736
737```js
738router.replace({
739  url: 'pages/detail',
740  params: {
741    data1: 'message'
742  }
743});
744```
745
746## router.enableAlertBeforeBackPage<sup>(deprecated)</sup>
747
748enableAlertBeforeBackPage(options: EnableAlertOptions): void
749
750Enables the display of a confirm dialog box before returning to the previous page.
751
752This API is deprecated since API version 9. You are advised to use [showAlertBeforeBackPage<sup>9+</sup>](#routershowalertbeforebackpage9) instead.
753
754**System capability**: SystemCapability.ArkUI.ArkUI.Full
755
756**Parameters**
757
758| Name    | Type                                      | Mandatory  | Description       |
759| ------- | ---------------------------------------- | ---- | --------- |
760| options | [EnableAlertOptions](#enablealertoptions) | Yes   | Description of the dialog box.|
761
762**Example**
763
764  ```js
765  router.enableAlertBeforeBackPage({
766    message: 'Message Info'
767  });
768  ```
769
770## router.disableAlertBeforeBackPage<sup>(deprecated)</sup>
771
772disableAlertBeforeBackPage(): void
773
774Disables the display of a confirm dialog box before returning to the previous page.
775
776This API is deprecated since API version 9. You are advised to use [hideAlertBeforeBackPage<sup>9+</sup>](#routerhidealertbeforebackpage9) instead.
777
778**System capability**: SystemCapability.ArkUI.ArkUI.Full
779
780**Example**
781
782```js
783router.disableAlertBeforeBackPage();
784```
785