js-apis-arkui-UIContext.md 57.4 KB
Newer Older
E
ester.zhou 已提交
1 2
# @ohos.arkui.UIContext (UIContext)

E
ester.zhou 已提交
3
In the stage model, a window stage or window can use the **loadContent** API to load pages, create a UI instance, and render page content to the associated window. Naturally, UI instances and windows are associated on a one-by-one basis. Some global UI APIs are executed in the context of certain UI instances. When calling these APIs, you must identify the UI context, and consequently UI instance, by tracing the call chain. If these APIs are called on a non-UI page or in some asynchronous callback, the current UI context may fail to be identified, resulting in API execution errors.
E
ester.zhou 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

**@ohos.window** adds the [getUIContext](./js-apis-window.md#getuicontext10) API in API version 10 for obtaining the **UIContext** object of a UI instance. The API provided by the **UIContext** object can be directly applied to the corresponding UI instance.

> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.

## UIContext

In the following API examples, you must first use [getUIContext()](./js-apis-window.md#getuicontext10) in **@ohos.window** to obtain a **UIContext** instance, and then call the APIs using the obtained instance. In this document, the **UIContext** instance is represented by **uiContext**.

### getFont

getFont(): Font

Obtains a **Font** object.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type | Description         |
| ----- | ----------------- |
| [Font](#font) | **Font** object.|

**Example**

```ts
uiContext.getFont();
```
E
ester.zhou 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
### getComponentUtils

getComponentUtils(): ComponentUtils

Obtains the **ComponentUtils** object.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type | Description         |
| ----- | ----------------- |
| [ComponentUtils](#componentutils) | **ComponentUtils** object.|

**Example**

```ts
uiContext.getComponentUtils();
```

### getUIInspector

getUIInspector(): UIInspector

Obtains the **UIInspector** object.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type | Description         |
| ----- | ----------------- |
| [UInspector](#uiinspector) | **UIInspector** object.|

**Example**

```ts
uiContext.getUIInspector();
```
E
ester.zhou 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

### getMediaQuery

getMediaQuery(): MediaQuery

Obtains a **MediaQuery** object.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type | Description         |
| ----- | ----------------- |
| [MediaQuery](#mediaquery) | **MediaQuery** object.|

**Example**

```ts
uiContext.getMediaQuery();
```

### getRouter

getRouter(): Router

Obtains a **Router** object.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type | Description         |
| ----- | ----------------- |
| [Router](#router) | **Router** object.|

**Example**

```ts
uiContext.getRouter();
```

### getPromptAction

getPromptAction(): PromptAction

Obtains a **PromptAction** object.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type | Description         |
| ----- | ----------------- |
| [PromptAction](#promptaction) | **PromptAction** object.|

**Example**

```ts
uiContext.getPromptAction();
```

### animateTo

animateTo(value: AnimateParam, event: () => void): void

Applies a transition animation for state changes.

E
ester.zhou 已提交
142 143
**System capability**: SystemCapability.ArkUI.ArkUI.Full

E
ester.zhou 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
Since API version 9, this API is supported in ArkTS widgets.

**Parameters**

| Name           | Type       |       Mandatory    |        Description       |
| ---------------- | ------------ | -------------------- | -------------------- |
| value | [AnimateParam](../arkui-ts/ts-explicit-animation.md#animateparam) | Yes| Animation settings.|
| event | () => void | Yes| Closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function.|

**Example**

```ts
// xxx.ets
@Entry
@Component
struct AnimateToExample {
  @State widthSize: number = 250
  @State heightSize: number = 100
  @State rotateAngle: number = 0
  private flag: boolean = true

  build() {
    Column() {
      Button('change size')
        .width(this.widthSize)
        .height(this.heightSize)
        .margin(30)
        .onClick(() => {
          if (this.flag) {
            uiContext.animateTo({
              duration: 2000,
              curve: Curve.EaseOut,
              iterations: 3,
              playMode: PlayMode.Normal,
              onFinish: () => {
                console.info('play end')
              }
            }, () => {
              this.widthSize = 150
              this.heightSize = 60
            })
          } else {
            uiContext.animateTo({}, () => {
              this.widthSize = 250
              this.heightSize = 100
            })
          }
          this.flag = !this.flag
        })
      Button('change rotate angle')
        .margin(50)
        .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
        .onClick(() => {
          uiContext.animateTo({
            duration: 1200,
            curve: Curve.Friction,
            delay: 500,
            iterations: -1, // The value -1 indicates that the animation is played for an unlimited number of times.
            playMode: PlayMode.Alternate,
            onFinish: () => {
              console.info('play end')
            }
          }, () => {
            this.rotateAngle = 90
          })
        })
    }.width('100%').margin({ top: 5 })
  }
}
```

### showAlertDialog

showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons): void

Shows an alert dialog box.

E
ester.zhou 已提交
221 222
**System capability**: SystemCapability.ArkUI.ArkUI.Full

E
ester.zhou 已提交
223 224
**Parameters**

E
ester.zhou 已提交
225 226 227 228
| Name   | Type | Mandatory| Description|
| ---- | --------------- | -------- | -------- |
| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons) | Yes| Defines and displays the **\<AlertDialog>** component.|

E
ester.zhou 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

**Example**

```ts
uiContext.showAlertDialog(
  {
    title: 'title',
    message: 'text',
    autoCancel: true,
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -20 },
    gridCount: 3,
    confirm: {
      value: 'button',
      action: () => {
        console.info('Button-clicking callback')
      }
    },
    cancel: () => {
      console.info('Closed callbacks')
    }
  }
)
```

### showActionSheet

showActionSheet(value: ActionSheetOptions): void

Defines and shows the action sheet.

E
ester.zhou 已提交
260 261
**System capability**: SystemCapability.ArkUI.ArkUI.Full

E
ester.zhou 已提交
262 263
**ActionSheetOptions parameters**

E
ester.zhou 已提交
264
| Name       | Type                   | Mandatory | Description                       |
E
ester.zhou 已提交
265
| ---------- | -------------------------- | ------- | ----------------------------- |
E
ester.zhou 已提交
266 267
| title      | [Resource](../arkui-ts/ts-types.md#resource) \| string | Yes    |  Title of the dialog box.|
| message    | [Resource](../arkui-ts/ts-types.md#resource) \| string | Yes    | Content of the dialog box. |
E
ester.zhou 已提交
268
| autoCancel | boolean                           | No    | Whether to close the dialog box when the overlay is clicked.<br>Default value: **true**|
E
ester.zhou 已提交
269 270
| confirm    | {<br>value: [ResourceStr](../arkui-ts/ts-types.md#resourcestr),<br>action: () =&gt; void<br>} | No | Text content of the confirm button and callback upon button clicking.<br>Default value:<br>**value**: button text.<br>**action**: callback upon button clicking.|
| cancel     | () =&gt; void           | No    | Callback invoked when the dialog box is closed after the overlay is clicked.  |
E
ester.zhou 已提交
271
| alignment  | [DialogAlignment](../arkui-ts/ts-methods-alert-dialog-box.md#dialogalignment) | No    |  Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Bottom**|
E
ester.zhou 已提交
272
| offset     | {<br>dx: [Length](../arkui-ts/ts-types.md#length),<br>dy: [Length](../arkui-ts/ts-types.md#length)<br>} | No     | Offset of the dialog box relative to the alignment position.{<br>dx: 0,<br>dy: 0<br>} |
E
ester.zhou 已提交
273 274 275 276
| sheets     | Array&lt;SheetInfo&gt; | Yes      | Options in the dialog box. Each option supports the image, text, and callback.|

**SheetInfo parameters**

E
ester.zhou 已提交
277
| Name| Type                                                    | Mandatory| Description       |
E
ester.zhou 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
| ------ | ------------------------------------------------------------ | ---- | ----------------- |
| title  | [ResourceStr](../arkui-ts/ts-types.md#resourcestr) | Yes  | Text of the option.      |
| icon   | [ResourceStr](../arkui-ts/ts-types.md#resourcestr) | No  | Sheet icon. By default, no icon is displayed.    |
| action | ()=&gt;void                                          | Yes  | Callback when the sheet is selected.|

**Example**

```ts
uiContext.showActionSheet({
  title: 'ActionSheet title',
  message: 'message',
  autoCancel: true,
  confirm: {
    value: 'Confirm button',
    action: () => {
      console.log('Get Alert Dialog handled')
    }
  },
  cancel: () => {
    console.log('actionSheet canceled')
  },
  alignment: DialogAlignment.Bottom,
  offset: { dx: 0, dy: -10 },
  sheets: [
    {
      title: 'apples',
      action: () => {
        console.log('apples')
      }
    },
    {
      title: 'bananas',
      action: () => {
        console.log('bananas')
      }
    },
    {
      title: 'pears',
      action: () => {
        console.log('pears')
      }
    }
  ]
})
```

### showDatePickerDialog

showDatePickerDialog(options: DatePickerDialogOptions): void

Shows a date picker dialog box.

E
ester.zhou 已提交
330 331
**System capability**: SystemCapability.ArkUI.ArkUI.Full

E
ester.zhou 已提交
332 333
**DatePickerDialogOptions parameters**

E
ester.zhou 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| start | Date | No| Start date of the picker.<br>Default value: **Date('1970-1-1')**|
| end | Date | No| End date of the picker.<br>Default value: **Date('2100-12-31')**|
| selected | Date | No| Selected date.<br>Default value: current system date|
| lunar | boolean | No| Whether to display the lunar calendar.<br>Default value: **false**|
| showTime | boolean | No| Whether to display the time item.<br>Default value: **false**|
| useMilitaryTime | boolean | No| Whether to display time in 24-hour format.<br>Default value: **false**|
| disappearTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.|
| textStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.|
| selectedTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.|
| onAccept | (value: [DatePickerResult](../arkui-ts/ts-basic-components-datepicker.md#datepickerresult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [DatePickerResult](../arkui-ts/ts-basic-components-datepicker.md#datepickerresult)) => void | No| Callback invoked when the selected item in the picker changes.|
E
ester.zhou 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

**Example**

```ts
let selectedDate: Date = new Date("2010-1-1")
uiContext.showDatePickerDialog({
  start: new Date("2000-1-1"),
  end: new Date("2100-12-31"),
  selected: selectedDate,
  onAccept: (value: DatePickerResult) => {
    // Use the setFullYear method to set the date when the OK button is touched. In this way, when the date picker dialog box is displayed again, the selected date is the date last confirmed.
    selectedDate.setFullYear(value.year, value.month, value.day)
    console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
  },
  onCancel: () => {
    console.info("DatePickerDialog:onCancel()")
  },
  onChange: (value: DatePickerResult) => {
    console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
  }
})
```

### showTimePickerDialog

showTimePickerDialog(options: TimePickerDialogOptions): void

Shows a time picker dialog box.

E
ester.zhou 已提交
377 378
**System capability**: SystemCapability.ArkUI.ArkUI.Full

E
ester.zhou 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
**TimePickerDialogOptions parameters**

| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| selected | Date | No| Selected time.<br>Default value: current system time|
| useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.<br>Default value: **false**|
| disappearTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.|
| textStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.|
| selectedTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.|
| onAccept | (value: [TimePickerResult](../arkui-ts/ts-basic-components-timepicker.md#timepickerresult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [TimePickerResult](../arkui-ts/ts-basic-components-timepicker.md#timepickerresult)) => void | No| Callback invoked when the selected time changes.|

**Example**

```ts
let selectTime: Date = new Date('2020-12-25T08:30:00')
uiContext.showTimePickerDialog({
  selected: this.selectTime,
  onAccept: (value: TimePickerResult) => {
    // Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time.
    this.selectTime.setHours(value.hour, value.minute)
    console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
  },
  onCancel: () => {
    console.info("TimePickerDialog:onCancel()")
  },
  onChange: (value: TimePickerResult) => {
    console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
  }
})
```

### showTextPickerDialog

showTextPickerDialog(options: TextPickerDialogOptions): void

Shows a text picker in the given settings.

E
ester.zhou 已提交
418 419
**System capability**: SystemCapability.ArkUI.ArkUI.Full

E
ester.zhou 已提交
420 421
**TextPickerDialogOptions parameters**

E
ester.zhou 已提交
422
| Name| Type| Mandatory| Description|
E
ester.zhou 已提交
423
| -------- | -------- | -------- |  -------- |
E
ester.zhou 已提交
424
| range | string[] \| [Resource](../arkui-ts/ts-types.md#resource)\|[TextPickerRangeContent](../arkui-ts/ts-basic-components-textpicker.md#textpickerrangecontent10)[] | Yes|  Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed.|
E
ester.zhou 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
| selected | number | No|  Index of the selected item.<br>Default value: **0**|
| value       | string           | No   | Text of the selected item. This parameter does not take effect when the **selected** parameter is set. If the value is not within the range, the first item in the range is used instead.|
| defaultPickerItemHeight | number \| string | No| Height of the picker item.|
| disappearTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.|
| textStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.|
| selectedTextStyle | [PickerTextStyle](../arkui-ts/ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.|
| onAccept | (value: [TextPickerResult](../arkui-ts/ts-methods-textpicker-dialog.md#textpickerresult)) => void | No|  Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [TextPickerResult](../arkui-ts/ts-methods-textpicker-dialog.md#textpickerresult)) => void | No|  Callback invoked when the selected item changes.|

**Example**

```ts
let select: number = 2
let fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5']
uiContext.showTextPickerDialog({
  range: this.fruits,
  selected: this.select,
  onAccept: (value: TextPickerResult) => {
    // Set select to the index of the item selected when the OK button is touched. In this way, when the text picker dialog box is displayed again, the selected item is the one last confirmed.
    this.select = value.index
    console.info("TextPickerDialog:onAccept()" + JSON.stringify(value))
  },
  onCancel: () => {
    console.info("TextPickerDialog:onCancel()")
  },
  onChange: (value: TextPickerResult) => {
    console.info("TextPickerDialog:onChange()" + JSON.stringify(value))
  }
})
```

### createAnimator

createAnimator(options: AnimatorOptions): AnimatorResult

Creates an **Animator** object.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                                 | Mandatory  | Description     |
| ------- | ----------------------------------- | ---- | ------- |
| options | [AnimatorOptions](./js-apis-animator.md#animatoroptions) | Yes   | Animator options.|

**Return value**

| Type                               | Description           |
| --------------------------------- | ------------- |
| [AnimatorResult](./js-apis-animator.md#animatorresult) | Animator result.|

**Example**

```ts
let options = {
  duration: 1500,
  easing: "friction",
  delay: 0,
  fill: "forwards",
  direction: "normal",
  iterations: 3,
  begin: 200.0,
  end: 400.0
};
uiContext.createAnimator(options);
```

### runScopedTask

runScopedTask(callback: () => void): void

Executes the specified callback in this UI context.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                                 | Mandatory  | Description     |
| ------- | ----------------------------------- | ---- | ------- |
| callback | () => void            | Yes   | Callback used to return the result.|

**Example**

```ts
uiContext.runScopedTask(
  () => {
    console.log('Succeeded in runScopedTask');
  }
);
```

## Font

In the following API examples, you must first use [getFont()](#getfont) in **UIContext** to obtain a **Font** instance, and then call the APIs using the obtained instance.

### registerFont

E
ester.zhou 已提交
523
registerFont(options: font.FontOptions): void
E
ester.zhou 已提交
524 525 526 527 528 529 530

Registers a custom font with the font manager.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
531 532 533
| Name | Type                                           | Mandatory| Description                  |
| ------- | ----------------------------------------------- | ---- | ---------------------- |
| options | [font.FontOptions](js-apis-font.md#fontoptions) | Yes  | Information about the custom font to register.|
E
ester.zhou 已提交
534 535 536 537 538 539 540 541 542 543

**Example**

```ts
let font = uiContext.getFont();
font.registerFont({
  familyName: 'medium',
  familySrc: '/font/medium.ttf'
});
```
E
ester.zhou 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
### getStstemFontList

getSystemFontList(): Array\<string> 

Obtains the list of supported fonts.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type          | Description              |
| -------------- | ------------------ |
| Array\<string> | List of supported fonts.|

**Example**

```ts
let font = uiContext.getFont();
font.getSystemFontList()
```

### getFontByName

getFontByName(fontName: string): font.FontInfo

Obtains information about a system font based on the font name.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name  | Type  | Mandatory| Description          |
| -------- | ------ | ---- | -------------- |
| fontName | string | Yes  | System font name.|

**Return value**

| Type                                | Description          |
| ------------------------------------ | -------------- |
| [FontInfo](js-apis-font.md#fontinfo10) | Information about the system font.|

**Example**

```ts
let font = uiContext.getFont();
font.getFontByName('Sans Italic')
```

E
ester.zhou 已提交
592 593 594 595 596 597
## ComponentUtils

In the following API examples, you must first use [getComponentUtils()](#getcomponentutils) in **UIContext** to obtain a **ComponentUtils** instance, and then call the APIs using the obtained instance.

### getRectangleById

E
ester.zhou 已提交
598
getRectangleById(id: string): componentUtils.ComponentInfo
E
ester.zhou 已提交
599 600 601 602 603 604 605 606 607

Obtains the size, position, translation, scaling, rotation, and affine matrix information of the specified component.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name| Type  | Mandatory| Description            |
| ------ | ------ | ---- | ---------------- |
E
ester.zhou 已提交
608
| id     | string | Yes  | Unique component ID.|
E
ester.zhou 已提交
609 610 611

**Return value**

E
ester.zhou 已提交
612 613 614
| Type                                                    | Description                                            |
| -------------------------------------------------------- | ------------------------------------------------ |
| [ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | Size, position, translation, scaling, rotation, and affine matrix information of the component.|
E
ester.zhou 已提交
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630

**Example**

```ts
let componentUtils = uiContext.getComponentUtils();
let modePosition = componentUtils.getRectangleById("onClick");
let localOffsetWidth = modePosition.size.width;
let localOffsetHeight = modePosition.size.height;
```

## UIInspector

In the following API examples, you must first use [getUIInspector()](#getuiinspector) in **UIContext** to obtain a **UIInspector** instance, and then call the APIs using the obtained instance.

### createComponentObserver

E
ester.zhou 已提交
631
createComponentObserver(id: string): inspector.ComponentObserver
E
ester.zhou 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644

Creates an observer for the specified component.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                         | Mandatory  | Description         |
| ------- | --------------------------- | ---- | ----------- |
| id | string | Yes   | Component ID.|

**Return value**

E
ester.zhou 已提交
645 646
| Type                                                        | Description                                              |
| ------------------------------------------------------------ | -------------------------------------------------- |
E
ester.zhou 已提交
647 648 649 650 651 652 653 654
| [ComponentObserver](js-apis-arkui-inspector.md#componentobserver) | Component observer, which is used to register and unregister listeners for completion of component layout or drawing.|

**Example**

```ts
let inspector = uiContext.getUIInspector();
let listener = inspector.createComponentObserver('COMPONENT_ID');
```
E
ester.zhou 已提交
655 656 657 658 659 660 661

## MediaQuery

In the following API examples, you must first use [getMediaQuery()](#getmediaquery) in **UIContext** to obtain a **MediaQuery** instance, and then call the APIs using the obtained instance.

### matchMediaSync

E
ester.zhou 已提交
662
matchMediaSync(condition: string): mediaQuery.MediaQueryListener
E
ester.zhou 已提交
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

Sets the media query criteria and returns the corresponding listening handle.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name      | Type    | Mandatory  | Description                                      |
| --------- | ------ | ---- | ---------------------------------------- |
| condition | string | Yes   | Media query condition. For details, see [Syntax](../../ui/arkts-layout-development-media-query.md#syntax).|

**Return value**

| Type                | Description                    |
| ------------------ | ---------------------- |
| MediaQueryListener | Listening handle to a media event, which is used to register or deregister the listening callback.|

**Example**

```ts
let mediaquery = uiContext.getMediaQuery();
let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
```

## Router

In the following API examples, you must first use [getRouter()](#getrouter) in **UIContext** to obtain a **Router** instance, and then call the APIs using the obtained instance.

### pushUrl

E
ester.zhou 已提交
693
pushUrl(options: router.RouterOptions): Promise&lt;void&gt;
E
ester.zhou 已提交
694 695 696 697 698 699 700

Navigates to a specified page in the application.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
701 702 703
| Name | Type                                                   | Mandatory| Description              |
| ------- | ------------------------------------------------------- | ---- | ------------------ |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes  | Page routing parameters.|
E
ester.zhou 已提交
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

**Return value**

| Type               | Description       |
| ------------------- | --------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |
| 100002    | if the uri is not exist. |
| 100003    | if the pages are pushed too much. |

**Example**

```ts
let router = uiContext.getRouter();
router.pushUrl({
  url: 'pages/routerpage2',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
    }
  }
})
  .then(() => {
    // success
  })
  .catch(err => {
    console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
  })
```

### pushUrl

E
ester.zhou 已提交
744
pushUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): void
E
ester.zhou 已提交
745 746 747 748 749 750 751 752 753

Navigates to a specified page in the application.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                             | Mandatory  | Description       |
| ------- | ------------------------------- | ---- | --------- |
E
ester.zhou 已提交
754
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters.|
E
ester.zhou 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |
| 100002    | if the uri is not exist. |
| 100003    | if the pages are pushed too much. |

**Example**

```ts
let router = uiContext.getRouter();
router.pushUrl({
  url: 'pages/routerpage2',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
    }
  }
}, (err) => {
  if (err) {
    console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('pushUrl success');
})
```

### pushUrl

E
ester.zhou 已提交
790
pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
E
ester.zhou 已提交
791 792 793 794 795 796 797

Navigates to a specified page in the application.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
798 799 800 801
| Name | Type                                                   | Mandatory| Description                |
| ------- | ------------------------------------------------------- | ---- | -------------------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes  | Page routing parameters.  |
| mode    | [router.RouterMode](js-apis-router.md#routermode9)      | Yes  | Routing mode.|
E
ester.zhou 已提交
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841

**Return value**

| Type               | Description       |
| ------------------- | --------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |
| 100002    | if the uri is not exist. |
| 100003    | if the pages are pushed too much. |

**Example**

```ts
let router = uiContext.getRouter();
router.pushUrl({
  url: 'pages/routerpage2',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
    }
  }
}, router.RouterMode.Standard)
  .then(() => {
    // success
  })
  .catch(err => {
    console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
  })
```

### pushUrl

E
ester.zhou 已提交
842
pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
E
ester.zhou 已提交
843 844 845 846 847 848 849 850 851

Navigates to a specified page in the application.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                             | Mandatory  | Description        |
| ------- | ------------------------------- | ---- | ---------- |
E
ester.zhou 已提交
852 853
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters. |
| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
E
ester.zhou 已提交
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |
| 100002    | if the uri is not exist. |
| 100003    | if the pages are pushed too much. |

**Example**

```ts
let router = uiContext.getRouter();
router.pushUrl({
  url: 'pages/routerpage2',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
    }
  }
}, router.RouterMode.Standard, (err) => {
  if (err) {
    console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('pushUrl success');
})
```

### replaceUrl

E
ester.zhou 已提交
889
replaceUrl(options: router.RouterOptions): Promise&lt;void&gt;
E
ester.zhou 已提交
890 891 892

Replaces the current page with another one in the application and destroys the current page.

E
ester.zhou 已提交
893
**System capability**: SystemCapability.ArkUI.ArkUI.Full
E
ester.zhou 已提交
894 895 896

**Parameters**

E
ester.zhou 已提交
897 898 899
| Name | Type                                                   | Mandatory| Description              |
| ------- | ------------------------------------------------------- | ---- | ------------------ |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes  | Description of the new page.|
E
ester.zhou 已提交
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935

**Return value**

| Type               | Description       |
| ------------------- | --------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found, only throw in standard system. |
| 200002    | if the uri is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.replaceUrl({
  url: 'pages/detail',
  params: {
    data1: 'message'
  }
})
  .then(() => {
    // success
  })
  .catch(err => {
    console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
  })
```

### replaceUrl

E
ester.zhou 已提交
936
replaceUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): void
E
ester.zhou 已提交
937 938 939

Replaces the current page with another one in the application and destroys the current page.

E
ester.zhou 已提交
940
**System capability**: SystemCapability.ArkUI.ArkUI.Full
E
ester.zhou 已提交
941 942 943 944 945

**Parameters**

| Name | Type                           | Mandatory| Description              |
| ------- | ------------------------------- | ---- | ------------------ |
E
ester.zhou 已提交
946
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes  | Description of the new page.|
E
ester.zhou 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found, only throw in standard system. |
| 200002    | if the uri is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.replaceUrl({
  url: 'pages/detail',
  params: {
    data1: 'message'
  }
}, (err) => {
  if (err) {
    console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('replaceUrl success');
})
```

### replaceUrl

E
ester.zhou 已提交
978
replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
E
ester.zhou 已提交
979 980 981

Replaces the current page with another one in the application and destroys the current page.

E
ester.zhou 已提交
982
**System capability**: SystemCapability.ArkUI.ArkUI.Full
E
ester.zhou 已提交
983 984 985

**Parameters**

E
ester.zhou 已提交
986 987 988 989
| Name | Type                                                   | Mandatory| Description                |
| ------- | ------------------------------------------------------- | ---- | -------------------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes  | Description of the new page.  |
| mode    | [router.RouterMode](js-apis-router.md#routermode9)      | Yes  | Routing mode.|
E
ester.zhou 已提交
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009

**Return value**

| Type               | Description       |
| ------------------- | --------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if can not get the delegate, only throw in standard system. |
| 200002    | if the uri is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
E
ester.zhou 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
try {
  router.replaceUrl({
    url: 'pages/detail',
    params: {
      data1: 'message'
    }
  }, router.RouterMode.Standard)
} catch (err) {
  console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
}
E
ester.zhou 已提交
1020 1021 1022 1023
```

### replaceUrl

E
ester.zhou 已提交
1024
replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
E
ester.zhou 已提交
1025 1026 1027

Replaces the current page with another one in the application and destroys the current page.

E
ester.zhou 已提交
1028
**System capability**: SystemCapability.ArkUI.ArkUI.Full
E
ester.zhou 已提交
1029 1030 1031 1032 1033

**Parameters**

| Name    | Type                             | Mandatory  | Description        |
| ------- | ------------------------------- | ---- | ---------- |
E
ester.zhou 已提交
1034 1035
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Description of the new page. |
| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
E
ester.zhou 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found, only throw in standard system. |
| 200002    | if the uri is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.replaceUrl({
  url: 'pages/detail',
  params: {
    data1: 'message'
  }
}, router.RouterMode.Standard, (err) => {
  if (err) {
    console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('replaceUrl success');
});
```

### pushNamedRoute

E
ester.zhou 已提交
1067
pushNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
E
ester.zhou 已提交
1068 1069 1070 1071 1072 1073 1074

Navigates to a page using the named route. This API uses a promise to return the result.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1075 1076 1077
| Name | Type                                                        | Mandatory| Description              |
| ------- | ------------------------------------------------------------ | ---- | ------------------ |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes  | Page routing parameters.|
E
ester.zhou 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117

**Return value**

| Type               | Description       |
| ------------------- | --------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |
| 100003    | if the pages are pushed too much. |
| 100004    | if the named route is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.pushNamedRoute({
  name: 'myPage',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
    }
  }
})
  .then(() => {
    // success
  })
  .catch(err => {
    console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
  })
```

### pushNamedRoute

E
ester.zhou 已提交
1118
pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
E
ester.zhou 已提交
1119

E
ester.zhou 已提交
1120
Navigates to a page using the named route. This API uses a promise to return the result.
E
ester.zhou 已提交
1121 1122 1123 1124 1125 1126 1127

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                             | Mandatory  | Description       |
| ------- | ------------------------------- | ---- | --------- |
E
ester.zhou 已提交
1128
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters.|
E
ester.zhou 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |
| 100003    | if the pages are pushed too much. |
| 100004    | if the named route is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.pushNamedRoute({
  name: 'myPage',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
    }
  }
}, (err) => {
  if (err) {
    console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('pushNamedRoute success');
})
```
### pushNamedRoute

E
ester.zhou 已提交
1163
pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
E
ester.zhou 已提交
1164 1165 1166 1167 1168 1169 1170

Navigates to a page using the named route. This API uses a promise to return the result.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1171 1172 1173 1174
| Name | Type                                                        | Mandatory| Description                |
| ------- | ------------------------------------------------------------ | ---- | -------------------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes  | Page routing parameters.  |
| mode    | [router.RouterMode](js-apis-router.md#routermode9)           | Yes  | Routing mode.|
E
ester.zhou 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

**Return value**

| Type               | Description       |
| ------------------- | --------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |
| 100003    | if the pages are pushed too much. |
| 100004    | if the named route is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.pushNamedRoute({
  name: 'myPage',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
    }
  }
}, router.RouterMode.Standard)
  .then(() => {
    // success
  })
  .catch(err => {
    console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
  })
```

### pushNamedRoute

E
ester.zhou 已提交
1215
pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
E
ester.zhou 已提交
1216

E
ester.zhou 已提交
1217
Navigates to a page using the named route. This API uses a promise to return the result.
E
ester.zhou 已提交
1218 1219 1220 1221 1222 1223 1224

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                             | Mandatory  | Description        |
| ------- | ------------------------------- | ---- | ---------- |
E
ester.zhou 已提交
1225 1226
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters. |
| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
E
ester.zhou 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |
| 100003    | if the pages are pushed too much. |
| 100004    | if the named route is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.pushNamedRoute({
  name: 'myPage',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
    }
  }
}, router.RouterMode.Standard, (err) => {
  if (err) {
    console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('pushNamedRoute success');
})
```

### replaceNamedRoute

E
ester.zhou 已提交
1262
replaceNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
E
ester.zhou 已提交
1263 1264 1265 1266 1267 1268 1269

Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1270 1271 1272
| Name | Type                                                        | Mandatory| Description              |
| ------- | ------------------------------------------------------------ | ---- | ------------------ |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes  | Description of the new page.|
E
ester.zhou 已提交
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

**Return value**

| Type               | Description       |
| ------------------- | --------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
E
ester.zhou 已提交
1286
| 100001    | if UI execution context not found, only throw in standard system. |
E
ester.zhou 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
| 100004    | if the named route is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.replaceNamedRoute({
  name: 'myPage',
  params: {
    data1: 'message'
  }
})
  .then(() => {
    // success
  })
  .catch(err => {
    console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
  })
```

### replaceNamedRoute

E
ester.zhou 已提交
1309
replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
E
ester.zhou 已提交
1310

E
ester.zhou 已提交
1311
Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
E
ester.zhou 已提交
1312 1313 1314 1315 1316 1317 1318

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name | Type                           | Mandatory| Description              |
| ------- | ------------------------------- | ---- | ------------------ |
E
ester.zhou 已提交
1319
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes  | Description of the new page.|
E
ester.zhou 已提交
1320 1321 1322 1323 1324 1325 1326 1327
| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
E
ester.zhou 已提交
1328
| 100001    | if UI execution context not found, only throw in standard system. |
E
ester.zhou 已提交
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
| 100004    | if the named route is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.replaceNamedRoute({
  name: 'myPage',
  params: {
    data1: 'message'
  }
}, (err) => {
  if (err) {
    console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('replaceNamedRoute success');
})
```

### replaceNamedRoute

E
ester.zhou 已提交
1351
replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
E
ester.zhou 已提交
1352 1353 1354 1355 1356 1357 1358

Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1359 1360 1361 1362
| Name | Type                                                        | Mandatory| Description                |
| ------- | ------------------------------------------------------------ | ---- | -------------------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes  | Description of the new page.  |
| mode    | [router.RouterMode](js-apis-router.md#routermode9)           | Yes  | Routing mode.|
E
ester.zhou 已提交
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376


**Return value**

| Type               | Description       |
| ------------------- | --------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
E
ester.zhou 已提交
1377
| 100001    | if can not get the delegate, only throw in standard system. |
E
ester.zhou 已提交
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
| 100004    | if the named route is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.replaceNamedRoute({
  name: 'myPage',
  params: {
    data1: 'message'
  }
}, router.RouterMode.Standard)
  .then(() => {
    // success
  })
  .catch(err => {
    console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
  })
```

### replaceNamedRoute

E
ester.zhou 已提交
1400
replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
E
ester.zhou 已提交
1401

E
ester.zhou 已提交
1402
Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
E
ester.zhou 已提交
1403 1404 1405 1406 1407 1408 1409

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

| Name    | Type                             | Mandatory  | Description        |
| ------- | ------------------------------- | ---- | ---------- |
E
ester.zhou 已提交
1410 1411
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Description of the new page. |
| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
E
ester.zhou 已提交
1412 1413 1414 1415 1416 1417 1418 1419
| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.  |

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
E
ester.zhou 已提交
1420
| 100001    | if UI execution context not found, only throw in standard system. |
E
ester.zhou 已提交
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
| 100004    | if the named route is not exist. |

**Example**

```ts
let router = uiContext.getRouter();
router.replaceNamedRoute({
  name: 'myPage',
  params: {
    data1: 'message'
  }
}, router.RouterMode.Standard, (err) => {
  if (err) {
    console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('replaceNamedRoute success');
});
```

### back

E
ester.zhou 已提交
1443
back(options?: router.RouterOptions ): void
E
ester.zhou 已提交
1444 1445 1446 1447 1448 1449 1450

Returns to the previous page or a specified page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1451 1452 1453
| Name | Type                                                   | Mandatory| Description                                                        |
| ------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [router.RouterOptions](js-apis-router.md#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.|
E
ester.zhou 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500

**Example**

```ts
let router = uiContext.getRouter();
router.back({url:'pages/detail'});    
```

### clear

clear(): void

Clears all historical pages in the stack and retains only the current page at the top of the stack.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Example**

```ts
let router = uiContext.getRouter();
router.clear();    
```

### getLength

getLength(): string

Obtains the number of pages in the current stack.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type    | Description                |
| ------ | ------------------ |
| string | Number of pages in the stack. The maximum value is **32**.|

**Example**

```ts
let router = uiContext.getRouter();
let size = router.getLength();        
console.log('pages stack size = ' + size);    
```

### getState

E
ester.zhou 已提交
1501
getState(): router.RouterState
E
ester.zhou 已提交
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524

Obtains state information about the current page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type                         | Description     |
| --------------------------- | ------- |
| [RouterState](js-apis-router.md#routerstate) | Page routing state.|

**Example**

```ts
let router = uiContext.getRouter();
let page = router.getState();
console.log('current index = ' + page.index);
console.log('current name = ' + page.name);
console.log('current path = ' + page.path);
```

### showAlertBeforeBackPage

E
ester.zhou 已提交
1525
showAlertBeforeBackPage(options: router.EnableAlertOptions): void
E
ester.zhou 已提交
1526 1527 1528 1529 1530 1531 1532

Enables the display of a confirm dialog box before returning to the previous page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1533 1534 1535
| Name | Type                                                        | Mandatory| Description              |
| ------- | ------------------------------------------------------------ | ---- | ------------------ |
| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | Yes  | Description of the dialog box.|
E
ester.zhou 已提交
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548

**Error codes**

For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |

**Example**

```ts
let router = uiContext.getRouter();
E
ester.zhou 已提交
1549 1550 1551 1552 1553 1554 1555 1556 1557
router.showAlertBeforeBackPage({
  message: 'Message Info'
});
  .then(() => {
    // success
  })
  .catch(err => {
    console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`);
  })
E
ester.zhou 已提交
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
```

### hideAlertBeforeBackPage

hideAlertBeforeBackPage(): void

Disables the display of a confirm dialog box before returning to the previous page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Example**

```ts
let router = uiContext.getRouter();
router.hideAlertBeforeBackPage();    
```

### getParams

getParams(): Object

Obtains the parameters passed from the page that initiates redirection to the current page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

| Type  | Description                              |
| ------ | ---------------------------------- |
| object | Parameters passed from the page that initiates redirection to the current page.|

**Example**

```ts
let router = uiContext.getRouter();
router.getParams();
```

## PromptAction

In the following API examples, you must first use [getPromptAction()](#getpromptaction) in **UIContext** to obtain a **PromptAction** instance, and then call the APIs using the obtained instance.

### showToast

E
ester.zhou 已提交
1602
showToast(options: promptAction.ShowToastOptions): void
E
ester.zhou 已提交
1603 1604 1605 1606 1607 1608 1609

Shows a toast.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1610 1611 1612
| Name | Type                                                        | Mandatory| Description          |
| ------- | ------------------------------------------------------------ | ---- | -------------- |
| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | Yes  | Toast options.|
E
ester.zhou 已提交
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637

**Error codes**

For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |

**Example**

```ts
let promptAction = uiContext.getPromptAction();
try {
  promptAction.showToast({            
    message: 'Message Info',
    duration: 2000 
  });
} catch (error) {
  console.error(`showToast args error code is ${error.code}, message is ${error.message}`);
};
```

### showDialog

E
ester.zhou 已提交
1638
showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback&lt;promptAction.ShowDialogSuccessResponse&gt;): void
E
ester.zhou 已提交
1639 1640 1641 1642 1643 1644 1645

Shows a dialog box. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1646 1647 1648 1649
| Name  | Type                                                        | Mandatory| Description                    |
| -------- | ------------------------------------------------------------ | ---- | ------------------------ |
| options  | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes  | Dialog box options.|
| callback | AsyncCallback&lt;[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)&gt; | Yes  | Callback used to return the dialog box response result.    |
E
ester.zhou 已提交
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690

**Error codes**

For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |

**Example**

```ts
let promptAction = uiContext.getPromptAction();
try {
  promptAction.showDialog({
    title: 'showDialog Title Info',
    message: 'Message Info',
    buttons: [
      {
        text: 'button1',
        color: '#000000'
      },
      {
        text: 'button2',
        color: '#000000'
      }
    ]
  }, (err, data) => {
    if (err) {
      console.info('showDialog err: ' + err);
      return;
    }
    console.info('showDialog success callback, click button: ' + data.index);
  });
} catch (error) {
  console.error(`showDialog args error code is ${error.code}, message is ${error.message}`);
};
```

### showDialog

E
ester.zhou 已提交
1691
showDialog(options: promptAction.ShowDialogOptions): Promise&lt;promptAction.ShowDialogSuccessResponse&gt;
E
ester.zhou 已提交
1692 1693 1694 1695 1696 1697 1698

Shows a dialog box. This API uses a promise to return the result synchronously.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1699 1700 1701
| Name | Type                                                        | Mandatory| Description        |
| ------- | ------------------------------------------------------------ | ---- | ------------ |
| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes  | Dialog box options.|
E
ester.zhou 已提交
1702 1703 1704

**Return value**

E
ester.zhou 已提交
1705 1706 1707
| Type                                                        | Description            |
| ------------------------------------------------------------ | ---------------- |
| Promise&lt;[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)&gt; | Promise used to return the dialog box response result.|
E
ester.zhou 已提交
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748

**Error codes**

For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |

**Example**

```ts
let promptAction = uiContext.getPromptAction();
try {
  promptAction.showDialog({
    title: 'Title Info',
    message: 'Message Info',
    buttons: [
      {
        text: 'button1',
        color: '#000000'
      },
      {
        text: 'button2',
        color: '#000000'
      }
    ],
  })
    .then(data => {
      console.info('showDialog success, click button: ' + data.index);
    })
    .catch(err => {
      console.info('showDialog error: ' + err);
    })
} catch (error) {
  console.error(`showDialog args error code is ${error.code}, message is ${error.message}`);
};
```

### showActionMenu

E
ester.zhou 已提交
1749
showActionMenu(options: promptAction.ActionMenuOptions, callback:promptAction.ActionMenuSuccessResponse):void
E
ester.zhou 已提交
1750 1751 1752 1753 1754 1755 1756

Shows an action menu. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1757 1758 1759 1760
| Name  | Type                                                        | Mandatory| Description              |
| -------- | ------------------------------------------------------------ | ---- | ------------------ |
| options  | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes  | Action menu options.    |
| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | Yes  | Callback used to return the action menu response result.|
E
ester.zhou 已提交
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800

**Error codes**

For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |

**Example**

```ts
let promptAction = uiContext.getPromptAction();
try {
  promptAction.showActionMenu({
    title: 'Title Info',
    buttons: [
      {
        text: 'item1',
        color: '#666666'
      },
      {
        text: 'item2',
        color: '#000000'
      },
    ]
  }, (err, data) => {
    if (err) {
      console.info('showActionMenu err: ' + err);
      return;
    }
    console.info('showActionMenu success callback, click button: ' + data.index);
  })
} catch (error) {
  console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`);
};
```

### showActionMenu

E
ester.zhou 已提交
1801
showActionMenu(options: promptAction.ActionMenuOptions): Promise&lt;promptAction.ActionMenuSuccessResponse&gt;
E
ester.zhou 已提交
1802 1803 1804 1805 1806 1807 1808

Shows an action menu. This API uses a promise to return the result synchronously.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**

E
ester.zhou 已提交
1809 1810 1811
| Name | Type                                                        | Mandatory| Description          |
| ------- | ------------------------------------------------------------ | ---- | -------------- |
| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes  | Action menu options.|
E
ester.zhou 已提交
1812 1813 1814

**Return value**

E
ester.zhou 已提交
1815 1816 1817
| Type                                                        | Description          |
| ------------------------------------------------------------ | -------------- |
| Promise&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt; | Promise used to return the action menu response result.|
E
ester.zhou 已提交
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854

**Error codes**

For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).

| ID  | Error Message|
| --------- | ------- |
| 100001    | if UI execution context not found. |

**Example**

```ts
let promptAction = uiContext.getPromptAction();
try {
  promptAction.showActionMenu({
    title: 'showActionMenu Title Info',
    buttons: [
      {
        text: 'item1',
        color: '#666666'
      },
      {
        text: 'item2',
        color: '#000000'
      },
    ]
  })
    .then(data => {
      console.info('showActionMenu success, click button: ' + data.index);
    })
    .catch(err => {
      console.info('showActionMenu error: ' + err);
    })
} catch (error) {
  console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`);
};
```