1# Developing a JS Widget 2 3 4The following describes how to develop JS widgets based on the web-like development paradigm. 5 6 7## Working Principles 8 9Below shows the working principles of the widget framework. 10 11**Figure 1** Widget framework working principles in the stage model 12 13 14 15The widget host consists of the following modules: 16 17- Widget usage: provides operations such as creating, deleting, or updating a widget. 18 19- Communication adapter: provided by the SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. 20 21The Widget Manager consists of the following modules: 22 23- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. 24 25- Cache manager: caches view information of a widget after it is added to the Widget Manager. This enables the cached data to be directly returned when the widget is obtained next time, greatly reducing the latency. 26 27- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. 28 29- Object manager: manages RPC objects of the widget host. It is used to verify requests from the widget host and process callbacks after the widget update. 30 31- Communication adapter: communicates with the widget host and provider through RPCs. 32 33The widget provider consists of the following modules: 34 35- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. 36 37- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. 38 39- Communication adapter: provided by the SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. 40 41> **NOTE** 42> 43> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. 44 45 46## Available APIs 47 48The **FormExtensionAbility** class has the following APIs. For details, see [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md). 49 50| Name | Description | 51| -------- | -------- | 52| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget is being created. | 53| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget is being converted to a normal one. | 54| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget is being updated. | 55| onChangeFormVisibility(newStatus: Record<string, number>): void | Called to notify the widget provider that the widget visibility status is being changed. | 56| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to process a widget event. | 57| onRemoveForm(formId: string): void | Called to notify the widget provider that a widget is being destroyed. | 58| onConfigurationUpdate(newConfig: Configuration): void | Called when the configuration of the environment where the widget is running is being updated. | 59| onShareForm?(formId: string): Record<string, Object> | Called to notify the widget provider that the widget host is sharing the widget data. | 60 61The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis-form-kit/js-apis-app-form-formProvider.md). 62 63| Name | Description | 64| -------- | -------- | 65| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void | Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result. | 66| setFormNextRefreshTime(formId: string, minute: number): Promise<void> | Sets the next refresh time for a widget. This API uses a promise to return the result. | 67| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback<void>): void | Updates a widget. This API uses an asynchronous callback to return the result. | 68| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void> | Updates a widget. This API uses a promise to return the result. | 69 70The **FormBindingData** class has the following APIs. For details, see [FormBindingData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md). 71 72| Name | Description | 73| -------- | -------- | 74| createFormBindingData(obj?: Object \| string): FormBindingData | Creates a **FormBindingData** object. | 75 76 77## How to Develop 78 79The widget provider development based on the [stage model](../application-models/stage-model-development-overview.md) involves the following key steps: 80 81- [Creating a FormExtensionAbility Instance](#creating-a-formextensionability-instance): Develop the lifecycle callback functions of FormExtensionAbility. 82 83- [Configuring the Widget Configuration Files](#configuring-the-widget-configuration-files): Configure the application configuration file **module.json5** and profile configuration file. 84 85- [Persistently Storing Widget Data](#persistently-storing-widget-data): Manage widget data persistence. 86 87- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed in a widget. 88 89- [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page. 90 91- [Developing Widget Events](#developing-widget-events): Add the router and message events for a widget. 92 93 94### Creating a FormExtensionAbility Instance 95 96To create a widget in the stage model, you need to implement the lifecycle callbacks of FormExtensionAbility. Create a widget template in DevEco Studio<!--RP1--> by referring to [Creating a Service Widget](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V2/ide_service_widget-0000001078566997-V2)<!--RP1End--> and then perform the following: 97 981. Import related modules to **EntryFormAbility.ets**. 99 ```ts 100 import { Want } from '@kit.AbilityKit'; 101 import { formBindingData, FormExtensionAbility, formInfo, formProvider } from '@kit.FormKit'; 102 import { hilog } from '@kit.PerformanceAnalysisKit'; 103 import { BusinessError } from '@kit.BasicServicesKit'; 104 105 const TAG: string = 'JsCardFormAbility'; 106 const DOMAIN_NUMBER: number = 0xFF00; 107 ``` 108 1092. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ets**. 110 111 ```ts 112 export default class EntryFormAbility extends FormExtensionAbility { 113 onAddForm(want: Want): formBindingData.FormBindingData { 114 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onAddForm'); 115 // Called when the widget is created. The widget provider should return the widget data binding class. 116 let obj: Record<string, string> = { 117 'title': 'titleOnCreate', 118 'detail': 'detailOnCreate' 119 }; 120 let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj); 121 return formData; 122 } 123 onCastToNormalForm(formId: string): void { 124 // Called when a temporary widget is being converted into a normal one. The widget provider should respond to the conversion. 125 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onCastToNormalForm'); 126 } 127 onUpdateForm(formId: string): void { 128 // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. 129 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onUpdateForm'); 130 let obj: Record<string, string> = { 131 'title': 'titleOnUpdate', 132 'detail': 'detailOnUpdate' 133 }; 134 let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj); 135 formProvider.updateForm(formId, formData).catch((error: BusinessError) => { 136 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); 137 }); 138 } 139 onChangeFormVisibility(newStatus: Record<string, number>): void { 140 // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. 141 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onChangeFormVisibility'); 142 //... 143 } 144 onFormEvent(formId: string, message: string): void { 145 // If the widget supports event triggering, override this method and implement the trigger. 146 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onFormEvent'); 147 } 148 onRemoveForm(formId: string): void { 149 // Delete widget data. 150 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onRemoveForm'); 151 //... 152 } 153 onAcquireFormState(want: Want): formInfo.FormState { 154 return formInfo.FormState.READY; 155 } 156 } 157 ``` 158 159> **NOTE** 160> 161> FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. 162 163 164### Configuring the Widget Configuration Files 165 1661. Configure ExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For a FormExtensionAbility, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information. 167 Example configuration: 168 169 170 ```json 171 { 172 "module": { 173 ... 174 "extensionAbilities": [ 175 { 176 "name": "JsCardFormAbility", 177 "srcEntry": "./ets/jscardformability/JsCardFormAbility.ts", 178 "description": "$string:JSCardFormAbility_desc", 179 "label": "$string:JSCardFormAbility_label", 180 "type": "form", 181 "metadata": [ 182 { 183 "name": "ohos.extension.form", 184 "resource": "$profile:form_jscard_config" 185 } 186 ] 187 } 188 ] 189 } 190 } 191 ``` 192 1932. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if **resource** is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal structure of the profile configuration file. 194 195 **Table 1** Widget profile configuration file 196 197 | Field | Description | Data Type | Default Value Allowed | 198 | -------- | -------- | -------- | -------- | 199 | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | 200 | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | 201 | src | Full path of the UI code corresponding to the widget. | String | No | 202 | window | Window-related configurations. | Object | Yes | 203 | isDefault | Whether the widget is a default one. Each UIAbility has only one default widget.<br>- **true**: The widget is the default one.<br>- **false**: The widget is not the default one. | Boolean | No | 204 | colorMode | Color mode of the widget.<br>- **auto**: auto-adaptive color mode<br>- **dark**: dark color mode<br>- **light**: light color mode | String | Yes (initial value: **auto**) | 205 | supportDimensions | Grid styles supported by the widget.<br>- **1 * 2**: indicates a grid with one row and two columns.<br>- **2 * 2**: indicates a grid with two rows and two columns.<br>- **2 * 4**: indicates a grid with two rows and four columns.<br>- **4 * 4**: indicates a grid with four rows and four columns. | String array | No | 206 | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget. | String | No | 207 | updateEnabled | Whether the widget can be updated periodically.<br>- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.<br>- **false**: The widget cannot be updated periodically. | Boolean | No | 208 | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used. | String | Yes (initial value: **0:0**) | 209 | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used. | Number | Yes (initial value: **0**) | 210 | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | 211 | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | 212 | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | 213 214 Example configuration: 215 216 217 ```json 218 { 219 "forms": [ 220 { 221 "name": "WidgetJS", 222 "description": "$string:JSCardEntryAbility_desc", 223 "src": "./js/WidgetJS/pages/index/index", 224 "window": { 225 "designWidth": 720, 226 "autoDesignWidth": true 227 }, 228 "colorMode": "auto", 229 "isDefault": true, 230 "updateEnabled": true, 231 "scheduledUpdateTime": "10:30", 232 "updateDuration": 1, 233 "defaultDimension": "2*2", 234 "supportDimensions": [ 235 "2*2" 236 ] 237 } 238 ] 239 } 240 ``` 241 242 243### Persistently Storing Widget Data 244 245A widget provider is usually started when it is needed to provide information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. 246 247 248```ts 249import { common, Want } from '@kit.AbilityKit'; 250import { hilog } from '@kit.PerformanceAnalysisKit'; 251import { formBindingData, FormExtensionAbility } from '@kit.FormKit'; 252import { BusinessError } from '@kit.BasicServicesKit'; 253import { preferences } from '@kit.ArkData'; 254 255const TAG: string = 'JsCardFormAbility'; 256const DATA_STORAGE_PATH: string = '/data/storage/el2/base/haps/form_store'; 257const DOMAIN_NUMBER: number = 0xFF00; 258 259let storeFormInfo = async (formId: string, formName: string, tempFlag: boolean, context: common.FormExtensionContext): Promise<void> => { 260 // Only the widget ID (formId), widget name (formName), and whether the widget is a temporary one (tempFlag) are persistently stored. 261 let formInfo: Record<string, string | boolean | number> = { 262 'formName': formName, 263 'tempFlag': tempFlag, 264 'updateCount': 0 265 }; 266 try { 267 const storage: preferences.Preferences = await preferences.getPreferences(context, DATA_STORAGE_PATH); 268 // put form info 269 await storage.put(formId, JSON.stringify(formInfo)); 270 hilog.info(DOMAIN_NUMBER, TAG, `[EntryFormAbility] storeFormInfo, put form info successfully, formId: ${formId}`); 271 await storage.flush(); 272 } catch (err) { 273 hilog.error(DOMAIN_NUMBER, TAG, `[EntryFormAbility] failed to storeFormInfo, err: ${JSON.stringify(err as BusinessError)}`); 274 } 275} 276 277export default class JsCardFormAbility extends FormExtensionAbility { 278 onAddForm(want: Want): formBindingData.FormBindingData { 279 hilog.info(DOMAIN_NUMBER, TAG, '[JsCardFormAbility] onAddForm'); 280 281 if (want.parameters) { 282 let formId = JSON.stringify(want.parameters['ohos.extra.param.key.form_identity']); 283 let formName = JSON.stringify(want.parameters['ohos.extra.param.key.form_name']); 284 let tempFlag = want.parameters['ohos.extra.param.key.form_temporary'] as boolean; 285 // Persistently store widget data for subsequent use, such as instance acquisition and update. 286 // Implement this API based on project requirements. 287 storeFormInfo(formId, formName, tempFlag, this.context); 288 } 289 290 let obj: Record<string, string> = { 291 'title': 'titleOnCreate', 292 'detail': 'detailOnCreate' 293 }; 294 let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj); 295 return formData; 296 } 297} 298``` 299 300You should override **onRemoveForm** to implement widget data deletion. 301 302 303```ts 304import { common } from '@kit.AbilityKit'; 305import { hilog } from '@kit.PerformanceAnalysisKit'; 306import { FormExtensionAbility } from '@kit.FormKit'; 307import { BusinessError } from '@kit.BasicServicesKit'; 308import { preferences } from '@kit.ArkData'; 309 310const TAG: string = 'JsCardFormAbility'; 311const DATA_STORAGE_PATH: string = '/data/storage/el2/base/haps/form_store'; 312const DOMAIN_NUMBER: number = 0xFF00; 313 314let deleteFormInfo = async (formId: string, context: common.FormExtensionContext): Promise<void> => { 315 try { 316 const storage: preferences.Preferences = await preferences.getPreferences(context, DATA_STORAGE_PATH); 317 // Delete the widget information. 318 await storage.delete(formId); 319 hilog.info(DOMAIN_NUMBER, TAG, `[EntryFormAbility] deleteFormInfo, del form info successfully, formId: ${formId}`); 320 await storage.flush(); 321 } catch (err) { 322 hilog.error(DOMAIN_NUMBER, TAG, `[EntryFormAbility] failed to deleteFormInfo, err: ${JSON.stringify(err as BusinessError)}`); 323 }; 324}; 325 326export default class JsCardFormAbility extends FormExtensionAbility { 327 onRemoveForm(formId: string): void { 328 // Delete widget data. 329 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onRemoveForm'); 330 // Delete the persistent widget instance data. 331 // Implement this API based on project requirements. 332 deleteFormInfo(formId, this.context); 333 } 334} 335``` 336 337For details about how to implement persistent data storage, see [Application Data Persistence](../database/app-data-persistence-overview.md). 338 339The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. 340 341- Normal widget: a widget persistently used by the widget host 342 343- Temporary widget: a widget temporarily used by the widget host 344 345Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake. 346 347 348### Updating Widget Data 349 350When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm()** to update the widget. 351 352 353```ts 354import { hilog } from '@kit.PerformanceAnalysisKit'; 355import { formBindingData, FormExtensionAbility, formProvider } from '@kit.FormKit'; 356import { BusinessError } from '@kit.BasicServicesKit'; 357 358const TAG: string = 'JsCardFormAbility'; 359const DOMAIN_NUMBER: number = 0xFF00; 360 361export default class EntryFormAbility extends FormExtensionAbility { 362 onUpdateForm(formId: string): void { 363 // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. 364 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onUpdateForm'); 365 let obj: Record<string, string> = { 366 'title': 'titleOnUpdate', 367 'detail': 'detailOnUpdate' 368 }; 369 let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj); 370 formProvider.updateForm(formId, formData).catch((error: BusinessError) => { 371 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); 372 }); 373 } 374} 375``` 376 377 378### Developing the Widget UI Page 379 380You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. This section describes how to develop a page shown below. 381 382 383 384- HML: uses web-like paradigm components to describe the widget page information. 385 386 387 ```html 388 <div class="container"> 389 <stack> 390 <div class="container-img"> 391 <image src="/common/widget.png" class="bg-img"></image> 392 </div> 393 <div class="container-inner"> 394 <text class="title">{{title}}</text> 395 <text class="detail_text" onclick="routerEvent">{{detail}}</text> 396 </div> 397 </stack> 398 </div> 399 ``` 400 401- CSS: defines style information about the web-like paradigm components in HML. 402 403 ```css 404 .container { 405 flex-direction: column; 406 justify-content: center; 407 align-items: center; 408 } 409 410 .bg-img { 411 flex-shrink: 0; 412 height: 100%; 413 } 414 415 .container-inner { 416 flex-direction: column; 417 justify-content: flex-end; 418 align-items: flex-start; 419 height: 100%; 420 width: 100%; 421 padding: 12px; 422 } 423 424 .title { 425 font-size: 19px; 426 font-weight: bold; 427 color: white; 428 text-overflow: ellipsis; 429 max-lines: 1; 430 } 431 432 .detail_text { 433 font-size: 16px; 434 color: white; 435 opacity: 0.66; 436 text-overflow: ellipsis; 437 max-lines: 1; 438 margin-top: 6px; 439 } 440 ``` 441 442- JSON: defines data and event interaction on the widget UI page. 443 444 ```json 445 { 446 "data": { 447 "title": "TitleDefault", 448 "detail": "TextDefault" 449 }, 450 "actions": { 451 "routerEvent": { 452 "action": "router", 453 "abilityName": "EntryAbility", 454 "params": { 455 "message": "add detail" 456 } 457 } 458 } 459 } 460 ``` 461 462 463### Developing Widget Events 464 465You can set router and message events for components on a widget. The router event applies to UIAbility redirection, and the message event applies to custom click events. 466 467The key steps are as follows: 468 4691. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. 470 4712. Set the router event. 472 473 - **action**: **"router"**, which indicates a router event. 474 - **abilityName**: name of the UIAbility to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name of the stage model created by DevEco Studio is EntryAbility. 475 - **params**: custom parameters passed to the target UIAbility. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target UIAbility. For example, in the lifecycle function **onCreate** of the MainAbility in the stage model, you can obtain **want** and its **parameters** field. 476 4773. Set the message event. 478 479 - **action**: **"message"**, which indicates a message event. 480 - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onFormEvent()**. 481 482The following are examples: 483 484- HML file: 485 486 ```html 487 <div class="container"> 488 <stack> 489 <div class="container-img"> 490 <image src="/common/CardWebImg.png" class="bg-img"></image> 491 <image src="/common/CardWebImgMatrix.png" 492 class="bottom-img"/> 493 </div> 494 <div class="container-inner"> 495 <text class="title" onclick="routerEvent">{{ title }}</text> 496 <text class="detail_text" onclick="messageEvent">{{ detail }}</text> 497 </div> 498 </stack> 499 </div> 500 ``` 501 502- CSS file: 503 504 ```css 505 .container { 506 flex-direction: column; 507 justify-content: center; 508 align-items: center; 509 } 510 511 .bg-img { 512 flex-shrink: 0; 513 height: 100%; 514 z-index: 1; 515 } 516 517 .bottom-img { 518 position: absolute; 519 width: 150px; 520 height: 56px; 521 top: 63%; 522 background-color: rgba(216, 216, 216, 0.15); 523 filter: blur(20px); 524 z-index: 2; 525 } 526 527 .container-inner { 528 flex-direction: column; 529 justify-content: flex-end; 530 align-items: flex-start; 531 height: 100%; 532 width: 100%; 533 padding: 12px; 534 } 535 536 .title { 537 font-family: HarmonyHeiTi-Medium; 538 font-size: 14px; 539 color: rgba(255, 255, 255, 0.90); 540 letter-spacing: 0.6px; 541 font-weight: 500; 542 width: 100%; 543 text-overflow: ellipsis; 544 max-lines: 1; 545 } 546 547 .detail_text { 548 ffont-family: HarmonyHeiTi; 549 font-size: 12px; 550 color: rgba(255, 255, 255, 0.60); 551 letter-spacing: 0.51px; 552 font-weight: 400; 553 text-overflow: ellipsis; 554 max-lines: 1; 555 margin-top: 6px; 556 width: 100%; 557 } 558 ``` 559 560- JSON file: 561 562 ```json 563 { 564 "data": { 565 "title": "TitleDefault", 566 "detail": "TextDefault" 567 }, 568 "actions": { 569 "routerEvent": { 570 "action": "router", 571 "abilityName": "JSCardEntryAbility", 572 "params": { 573 "info": "router info", 574 "message": "router message" 575 } 576 }, 577 "messageEvent": { 578 "action": "message", 579 "params": { 580 "detail": "message detail" 581 } 582 } 583 } 584 } 585 ``` 586 587 > **NOTE** 588 > 589 > **JSON Value** in **data** supports multi-level nested data. When updating data, ensure that complete data is carried. 590 591Assume that a widget is displaying the course information of Mr. Zhang on July 18, as shown in the following code snippet. 592 ```ts 593 "data": { 594 "Day": "07.18", 595 "teacher": { 596 "name": "Mr.Zhang", 597 "course": "Math" 598 } 599 } 600 ``` 601To update the widget content to the course information of Mr. Li on July 18, you must pass the complete data as follows, instead of only a single date item such as **name** or **course**: 602 ```ts 603 "teacher": { 604 "name": "Mr.Li", 605 "course": "English" 606 } 607 ``` 608 609 610- Receive the router event in UIAbility and obtain parameters. 611 612 ```ts 613 import UIAbility from '@ohos.app.ability.UIAbility'; 614 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 615 import Want from '@ohos.app.ability.Want'; 616 import hilog from '@ohos.hilog'; 617 618 const TAG: string = 'EtsCardEntryAbility'; 619 const DOMAIN_NUMBER: number = 0xFF00; 620 621 export default class EtsCardEntryAbility extends UIAbility { 622 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 623 if (want.parameters) { 624 let params: Record<string, Object> = JSON.parse(JSON.stringify(want.parameters.params)); 625 // Obtain the info parameter passed in the router event. 626 if (params.info === 'router info') { 627 // Execute the service logic. 628 hilog.info(DOMAIN_NUMBER, TAG, `router info: ${params.info}`); 629 } 630 // Obtain the message parameter passed in the router event. 631 if (params.message === 'router message') { 632 // Execute the service logic. 633 hilog.info(DOMAIN_NUMBER, TAG, `router message: ${params.message}`); 634 } 635 } 636 } 637 }; 638 ``` 639 640- Receive the message event in FormExtensionAbility and obtain parameters. 641 642 ```ts 643 import FormExtension from '@ohos.app.form.FormExtensionAbility'; 644 import hilog from '@ohos.hilog'; 645 646 const TAG: string = 'FormAbility'; 647 const DOMAIN_NUMBER: number = 0xFF00; 648 649 export default class FormAbility extends FormExtension { 650 onFormEvent(formId: string, message: string): void { 651 // If the widget supports event triggering, override this method and implement the trigger. 652 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onFormEvent'); 653 // Obtain the detail parameter passed in the message event. 654 let msg: Record<string, string> = JSON.parse(message); 655 if (msg.detail === 'message detail') { 656 // Execute the service logic. 657 hilog.info(DOMAIN_NUMBER, TAG, 'message info:' + msg.detail); 658 } 659 } 660 }; 661 ```