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. For details about how to generate a service widget template, see <!--RP1-->[Developing a Service Widget](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-service-widget-V5)<!--RP1End-->. 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 404 ```css 405 .container { 406 flex-direction: column; 407 justify-content: center; 408 align-items: center; 409 } 410 411 .bg-img { 412 flex-shrink: 0; 413 height: 100%; 414 } 415 416 .container-inner { 417 flex-direction: column; 418 justify-content: flex-end; 419 align-items: flex-start; 420 height: 100%; 421 width: 100%; 422 padding: 12px; 423 } 424 425 .title { 426 font-size: 19px; 427 font-weight: bold; 428 color: white; 429 text-overflow: ellipsis; 430 max-lines: 1; 431 } 432 433 .detail_text { 434 font-size: 16px; 435 color: white; 436 opacity: 0.66; 437 text-overflow: ellipsis; 438 max-lines: 1; 439 margin-top: 6px; 440 } 441 ``` 442 443- JSON: defines data and event interaction on the widget UI page. 444 445 446 ```json 447 { 448 "data": { 449 "title": "TitleDefault", 450 "detail": "TextDefault" 451 }, 452 "actions": { 453 "routerEvent": { 454 "action": "router", 455 "abilityName": "EntryAbility", 456 "params": { 457 "message": "add detail" 458 } 459 } 460 } 461 } 462 ``` 463 464 465### Developing Widget Events 466 467You 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. 468 469The key steps are as follows: 470 4711. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. 472 4732. Set the router event. 474 475 - **action**: **"router"**, which indicates a router event. 476 - **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. 477 - **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. 478 4793. Set the message event. 480 481 - **action**: **"message"**, which indicates a message event. 482 - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onFormEvent()**. 483 484The following are examples: 485 486- HML file: 487 488 489 ```html 490 <div class="container"> 491 <stack> 492 <div class="container-img"> 493 <image src="/common/CardWebImg.png" class="bg-img"></image> 494 <image src="/common/CardWebImgMatrix.png" 495 class="bottom-img"/> 496 </div> 497 <div class="container-inner"> 498 <text class="title" onclick="routerEvent">{{ title }}</text> 499 <text class="detail_text" onclick="messageEvent">{{ detail }}</text> 500 </div> 501 </stack> 502 </div> 503 ``` 504 505- CSS file: 506 507 508 ```css 509 .container { 510 flex-direction: column; 511 justify-content: center; 512 align-items: center; 513 } 514 515 .bg-img { 516 flex-shrink: 0; 517 height: 100%; 518 z-index: 1; 519 } 520 521 .bottom-img { 522 position: absolute; 523 width: 150px; 524 height: 56px; 525 top: 63%; 526 background-color: rgba(216, 216, 216, 0.15); 527 filter: blur(20px); 528 z-index: 2; 529 } 530 531 .container-inner { 532 flex-direction: column; 533 justify-content: flex-end; 534 align-items: flex-start; 535 height: 100%; 536 width: 100%; 537 padding: 12px; 538 } 539 540 .title { 541 font-family: HarmonyHeiTi-Medium; 542 font-size: 14px; 543 color: rgba(255, 255, 255, 0.90); 544 letter-spacing: 0.6px; 545 font-weight: 500; 546 width: 100%; 547 text-overflow: ellipsis; 548 max-lines: 1; 549 } 550 551 .detail_text { 552 ffont-family: HarmonyHeiTi; 553 font-size: 12px; 554 color: rgba(255, 255, 255, 0.60); 555 letter-spacing: 0.51px; 556 font-weight: 400; 557 text-overflow: ellipsis; 558 max-lines: 1; 559 margin-top: 6px; 560 width: 100%; 561 } 562 ``` 563 564- JSON file: 565 566 567 ```json 568 { 569 "data": { 570 "title": "TitleDefault", 571 "detail": "TextDefault" 572 }, 573 "actions": { 574 "routerEvent": { 575 "action": "router", 576 "abilityName": "JSCardEntryAbility", 577 "params": { 578 "info": "router info", 579 "message": "router message" 580 } 581 }, 582 "messageEvent": { 583 "action": "message", 584 "params": { 585 "detail": "message detail" 586 } 587 } 588 } 589 } 590 ``` 591 592 > **NOTE** 593 > 594 > **JSON Value** in **data** supports multi-level nested data. When updating data, ensure that complete data is carried. 595 596 Assume that a widget is displaying the course information of Mr. Zhang on July 18, as shown in the following code snippet. 597 ```ts 598 "data": { 599 "Day": "07.18", 600 "teacher": { 601 "name": "Mr.Zhang", 602 "course": "Math" 603 } 604 } 605 ``` 606 To 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**: 607 ```ts 608 "teacher": { 609 "name": "Mr.Li", 610 "course": "English" 611 } 612 ``` 613 614 615- Receive the router event in UIAbility and obtain parameters. 616 617 618 ```ts 619 import UIAbility from '@ohos.app.ability.UIAbility'; 620 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 621 import Want from '@ohos.app.ability.Want'; 622 import hilog from '@ohos.hilog'; 623 624 const TAG: string = 'EtsCardEntryAbility'; 625 const DOMAIN_NUMBER: number = 0xFF00; 626 627 export default class EtsCardEntryAbility extends UIAbility { 628 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 629 if (want.parameters) { 630 let params: Record<string, Object> = JSON.parse(JSON.stringify(want.parameters.params)); 631 // Obtain the info parameter passed in the router event. 632 if (params.info === 'router info') { 633 // Execute the service logic. 634 hilog.info(DOMAIN_NUMBER, TAG, `router info: ${params.info}`); 635 } 636 // Obtain the message parameter passed in the router event. 637 if (params.message === 'router message') { 638 // Execute the service logic. 639 hilog.info(DOMAIN_NUMBER, TAG, `router message: ${params.message}`); 640 } 641 } 642 } 643 }; 644 ``` 645 646- Receive the message event in FormExtensionAbility and obtain parameters. 647 648 649 ```ts 650 import FormExtension from '@ohos.app.form.FormExtensionAbility'; 651 import hilog from '@ohos.hilog'; 652 653 const TAG: string = 'FormAbility'; 654 const DOMAIN_NUMBER: number = 0xFF00; 655 656 export default class FormAbility extends FormExtension { 657 onFormEvent(formId: string, message: string): void { 658 // If the widget supports event triggering, override this method and implement the trigger. 659 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onFormEvent'); 660 // Obtain the detail parameter passed in the message event. 661 let msg: Record<string, string> = JSON.parse(message); 662 if (msg.detail === 'message detail') { 663 // Execute the service logic. 664 hilog.info(DOMAIN_NUMBER, TAG, 'message info:' + msg.detail); 665 } 666 } 667 }; 668 ``` 669