• 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## router.back
386
387back(options?: RouterOptions ): void
388
389Returns to the previous page or a specified page.
390
391**System capability**: SystemCapability.ArkUI.ArkUI.Full
392
393**Parameters**
394
395| Name | Type                           | Mandatory| Description                                                        |
396| ------- | ------------------------------- | ---- | ------------------------------------------------------------ |
397| 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 previous page is returned, and the page in the page stack is not reclaimed. It will be reclaimed after being popped up.|
398
399**Example**
400
401```js
402router.back({url:'pages/detail'});
403```
404
405## router.clear
406
407clear(): void
408
409Clears all historical pages in the stack and retains only the current page at the top of the stack.
410
411**System capability**: SystemCapability.ArkUI.ArkUI.Full
412
413**Example**
414
415```js
416router.clear();
417```
418
419## router.getLength
420
421getLength(): string
422
423Obtains the number of pages in the current stack.
424
425**System capability**: SystemCapability.ArkUI.ArkUI.Full
426
427**Return value**
428
429| Type    | Description                |
430| ------ | ------------------ |
431| string | Number of pages in the stack. The maximum value is **32**.|
432
433**Example**
434
435```js
436let size = router.getLength();
437console.log('pages stack size = ' + size);
438```
439
440## router.getState
441
442getState(): RouterState
443
444Obtains state information about the current page.
445
446**System capability**: SystemCapability.ArkUI.ArkUI.Full
447
448**Return value**
449
450| Type                         | Description     |
451| --------------------------- | ------- |
452| [RouterState](#routerstate) | Page routing state.|
453
454**Example**
455
456```js
457let page = router.getState();
458console.log('current index = ' + page.index);
459console.log('current name = ' + page.name);
460console.log('current path = ' + page.path);
461```
462
463## RouterState
464
465Describes the page routing state.
466
467**System capability**: SystemCapability.ArkUI.ArkUI.Full
468
469| Name | Type  | Mandatory| Description                                                        |
470| ----- | ------ | ---- | ------------------------------------------------------------ |
471| 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.|
472| name  | string | No  | Name of the current page, that is, the file name.                          |
473| path  | string | Yes  | Path of the current page.                                        |
474
475## router.showAlertBeforeBackPage<sup>9+</sup>
476
477showAlertBeforeBackPage(options: EnableAlertOptions): void
478
479Enables the display of a confirm dialog box before returning to the previous page.
480
481**System capability**: SystemCapability.ArkUI.ArkUI.Full
482
483**Parameters**
484
485| Name    | Type                                      | Mandatory  | Description       |
486| ------- | ---------------------------------------- | ---- | --------- |
487| options | [EnableAlertOptions](#enablealertoptions) | Yes   | Description of the dialog box.|
488
489**Error codes**
490
491For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).
492
493| ID  | Error Message|
494| --------- | ------- |
495| 100001    | if UI execution context not found. |
496
497**Example**
498
499  ```js
500try {
501  router.showAlertBeforeBackPage({
502    message: 'Message Info'
503  });
504} catch(error) {
505  console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`);
506}
507  ```
508## EnableAlertOptions
509
510Describes the confirm dialog box.
511
512**System capability**: SystemCapability.ArkUI.ArkUI.Full
513
514| Name     | Type    | Mandatory  | Description      |
515| ------- | ------ | ---- | -------- |
516| message | string | Yes   | Content displayed in the confirm dialog box.|
517
518## router.hideAlertBeforeBackPage<sup>9+</sup>
519
520hideAlertBeforeBackPage(): void
521
522Disables the display of a confirm dialog box before returning to the previous page.
523
524**System capability**: SystemCapability.ArkUI.ArkUI.Full
525
526**Example**
527
528```js
529router.hideAlertBeforeBackPage();
530```
531
532##  router.getParams
533
534getParams(): Object
535
536Obtains the parameters passed from the page that initiates redirection to the current page.
537
538**System capability**: SystemCapability.ArkUI.ArkUI.Full
539
540**Return value**
541
542| Type  | Description                              |
543| ------ | ---------------------------------- |
544| object | Parameters passed from the page that initiates redirection to the current page.|
545
546**Example**
547
548```
549router.getParams();
550```
551
552## RouterOptions
553
554Describes the page routing options.
555
556**System capability**: SystemCapability.ArkUI.ArkUI.Lite
557
558| Name  | Type  | Mandatory| Description                                                        |
559| ------ | ------ | ---- | ------------------------------------------------------------ |
560| 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.|
561| 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.|
562
563
564  > **NOTE**
565  >
566  > The page routing stack supports a maximum of 32 pages.
567
568## RouterMode<sup>9+</sup>
569
570Enumerates the routing modes.
571
572**System capability**: SystemCapability.ArkUI.ArkUI.Full
573
574| Name    | Description                                                        |
575| -------- | ------------------------------------------------------------ |
576| Standard | Standard 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 standard mode.|
577| 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 as a new page to the top of the stack.<br>If the URL of the target page does not exist in the page stack, the page is redirected to in standard mode.|
578
579## Examples
580
581### JavaScript-based Web-like Development Paradigm
582
583```js
584// Current page
585export default {
586  pushPage() {
587    router.push({
588      url: 'pages/detail/detail',
589      params: {
590        data1: 'message'
591      }
592    });
593  }
594}
595```
596```js
597// detail page
598export default {
599  onInit() {
600    console.info('showData1:' + router.getParams()['data1']);
601  }
602}
603```
604
605### TypeScript-based Declarative Development Paradigm
606
607```ts
608// Navigate to the target page through router.pushUrl with the params parameter carried.
609import router from '@ohos.router'
610
611@Entry
612@Component
613struct Index {
614  async  routePage() {
615    let options = {
616      url: 'pages/second',
617      params: {
618        text: 'This is the value on the first page.',
619        data: {
620          array: [12, 45, 78]
621        }
622      }
623    }
624    try {
625      await router.pushUrl(options)
626    } catch (err) {
627      console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`)
628    }
629  }
630
631  build() {
632    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
633      Text('This is the first page.')
634        .fontSize(50)
635        .fontWeight(FontWeight.Bold)
636      Button() {
637        Text('next page')
638          .fontSize(25)
639          .fontWeight(FontWeight.Bold)
640      }.type(ButtonType.Capsule)
641      .margin({ top: 20 })
642      .backgroundColor('#ccc')
643      .onClick(() => {
644        this.routePage()
645      })
646    }
647    .width('100%')
648    .height('100%')
649  }
650}
651```
652
653```ts
654// Receive the transferred parameters on the second page.
655import router from '@ohos.router'
656
657@Entry
658@Component
659struct Second {
660  private content: string = "This is the second page."
661  @State text: string = router.getParams()['text']
662  @State data: any = router.getParams()['data']
663  @State secondData : string = ''
664
665  build() {
666    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
667      Text(`${this.content}`)
668        .fontSize(50)
669        .fontWeight(FontWeight.Bold)
670      Text(this.text)
671        .fontSize(30)
672        .onClick(()=>{
673          this.secondData = (this.data.array[1]).toString()
674        })
675      .margin({top:20})
676      Text(`This is the data passed from the first page: ${this.secondData}`)
677        .fontSize(20)
678        .margin({top:20})
679        .backgroundColor('red')
680    }
681    .width('100%')
682    .height('100%')
683  }
684}
685```
686
687## router.push<sup>(deprecated)</sup>
688
689push(options: RouterOptions): void
690
691Navigates to a specified page in the application.
692
693This API is deprecated since API version 9. You are advised to use [pushUrl<sup>9+</sup>](#routerpushurl9) instead.
694
695**System capability**: SystemCapability.ArkUI.ArkUI.Full
696
697**Parameters**
698
699| Name    | Type                             | Mandatory  | Description       |
700| ------- | ------------------------------- | ---- | --------- |
701| options | [RouterOptions](#routeroptions) | Yes   | Page routing parameters.|
702
703
704**Example**
705
706```js
707router.push({
708  url: 'pages/routerpage2',
709  params: {
710    data1: 'message',
711    data2: {
712      data3: [123, 456, 789]
713    }
714  }
715});
716```
717
718## router.replace<sup>(deprecated)</sup>
719
720replace(options: RouterOptions): void
721
722Replaces the current page with another one in the application and destroys the current page.
723
724This API is deprecated since API version 9. You are advised to use [replaceUrl<sup>9+</sup>](#routerreplaceurl9) instead.
725
726**System capability**: SystemCapability.ArkUI.ArkUI.Lite
727
728**Parameters**
729
730| Name | Type                           | Mandatory| Description              |
731| ------- | ------------------------------- | ---- | ------------------ |
732| options | [RouterOptions](#routeroptions) | Yes  | Description of the new page.|
733
734**Example**
735
736```js
737router.replace({
738  url: 'pages/detail',
739  params: {
740    data1: 'message'
741  }
742});
743```
744
745## router.enableAlertBeforeBackPage<sup>(deprecated)</sup>
746
747enableAlertBeforeBackPage(options: EnableAlertOptions): void
748
749Enables the display of a confirm dialog box before returning to the previous page.
750
751This API is deprecated since API version 9. You are advised to use [showAlertBeforeBackPage<sup>9+</sup>](#routershowalertbeforebackpage9) instead.
752
753**System capability**: SystemCapability.ArkUI.ArkUI.Full
754
755**Parameters**
756
757| Name    | Type                                      | Mandatory  | Description       |
758| ------- | ---------------------------------------- | ---- | --------- |
759| options | [EnableAlertOptions](#enablealertoptions) | Yes   | Description of the dialog box.|
760
761**Example**
762
763  ```js
764  router.enableAlertBeforeBackPage({
765    message: 'Message Info'
766  });
767  ```
768
769## router.disableAlertBeforeBackPage<sup>(deprecated)</sup>
770
771disableAlertBeforeBackPage(): void
772
773Disables the display of a confirm dialog box before returning to the previous page.
774
775This API is deprecated since API version 9. You are advised to use [hideAlertBeforeBackPage<sup>9+</sup>](#routerhidealertbeforebackpage9) instead.
776
777**System capability**: SystemCapability.ArkUI.ArkUI.Full
778
779**Example**
780
781```js
782router.disableAlertBeforeBackPage();
783```
784