目录

Developing a JS Widget (FA Model)

The FA model is supported since API version 7, and no longer recommended. Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation for capability expansion. Now, the stage model is recommended for application development.

Available APIs

The FormAbility has the following APIs.

API Description
onCreate(want: Want): formBindingData.FormBindingData Notifies the widget provider that a widget has been created.
onCastToNormal(formId: string): void Notifies the widget provider that a temporary widget has been converted from a temporary widget to a normal widget.
onUpdate(formId: string): void Notifies the widget provider that a widget has been updated.
onVisibilityChange(newStatus: Record<string, number>): void Notifies the widget provider of widget visibility changes.
onEvent(formId: string, message: string): void Notifies the widget provider of a widget event.
onDestroy(formId: string): void Notifies the widget provider that a widget has been destroyed.
onAcquireFormState?(want: Want): formInfo.FormState Notifies the widget provider of a widget state query.
onShare?(formId: string): {[key: string]: any} Notifies the widget provider of widget sharing.
onShareForm?(formId: string): Record<string, Object> Notifies the widget provider of widget sharing. You are advised to use this API instead of onShare(). If this API is implemented, onShare() will not be triggered.

The FormProvider class provides the following APIs. For details about the APIs, see @ohos.app.form.formProvider (formProvider).

API Description
setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void; Sets the next refresh time for a specified widget. This API uses an asynchronous callback to return the result.
setFormNextRefreshTime(formId: string, minute: number): Promise<void>; Sets the next refresh time for a specified widget. This API uses a promise to return the result.
updateForm(formId: string, formBindingData: formBindingData.FormBindingData,callback: AsyncCallback<void>): void; Updates a widget. This API uses an asynchronous callback to return the result.
updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; Updates a widget. This API uses a promise to return the result.

The FormBindingData class provides the following APIs. For details about the APIs, see @ohos.app.form.formBindingData (formBindingData).

API Description
createFormBindingData(obj?: Object | string): FormBindingData Creates a FormBindingData object.

How to Develop

The widget provider development based on the FA model involves the following key steps:

[h2]Implementing Widget Lifecycle Callbacks

To create a widget in the FA model, implement the widget lifecycle callbacks. Before that, generate a widget template by referring to Creating a Service Widget.

  1. Import related modules to form.ts.

    import type featureAbility from '@ohos.ability.featureAbility';
    import type Want from '@ohos.app.ability.Want';
    import formBindingData from '@ohos.app.form.formBindingData';
    import formInfo from '@ohos.app.form.formInfo';
    import formProvider from '@ohos.app.form.formProvider';
    import dataPreferences from '@ohos.data.preferences';
    import hilog from '@ohos.hilog';
  2. Implement the widget lifecycle callbacks in form.ts.

    const TAG: string = '[Sample_FAModelAbilityDevelop]';
    const domain: number = 0xFF00;
    
    const DATA_STORAGE_PATH: string = 'form_store';
    let storeFormInfo = async (formId: string, formName: string, tempFlag: boolean, context: featureAbility.Context): Promise<void> => {
      // Here, only the widget name (formName) and whether it is a temporary widget (tempFlag) are persisted.
      let formInfo: Record<string, string | number | boolean> = {
        'formName': formName,
        'tempFlag': tempFlag,
        'updateCount': 0
      };
      try {
        const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
        // Put the widget information.
        await storage.put(formId, JSON.stringify(formInfo));
        hilog.info(domain, TAG, `storeFormInfo, put form info successfully, formId: ${formId}`);
        await storage.flush();
      } catch (err) {
        hilog.error(domain, TAG, `failed to storeFormInfo, err: ${JSON.stringify(err as Error)}`);
      }
    };
    
    let deleteFormInfo = async (formId: string, context: featureAbility.Context) => {
      try {
        const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
        // Delete the widget information.
        await storage.delete(formId);
        hilog.info(domain, TAG, `deleteFormInfo, del form info successfully, formId: ${formId}`);
        await storage.flush();
      } catch (err) {
        hilog.error(domain, TAG, `failed to deleteFormInfo, err: ${JSON.stringify(err)}`);
      }
    }
    
    class LifeCycle {
      onCreate: (want: Want) => formBindingData.FormBindingData = (want) => ({ data: '' });
      onCastToNormal: (formId: string) => void = (formId) => {
      };
      onUpdate: (formId: string) => void = (formId) => {
      };
      onVisibilityChange: (newStatus: Record<string, number>) => void = (newStatus) => {
      };
      onEvent: (formId: string, message: string) => void = (formId, message) => {
      };
      onDestroy: (formId: string) => void = (formId) => {
      };
      onAcquireFormState?: (want: Want) => formInfo.FormState = (want) => (0);
      onShareForm?: (formId: string) => Record<string, Object> = (formId) => {
        let obj: Record<string, number> = {
          'test': 1
        };
        return obj;
      };
    }
    
    let obj: LifeCycle = {
      onCreate(want: Want) {
        hilog.info(domain, TAG, 'FormAbility onCreate');
        if (want.parameters) {
          let formId = String(want.parameters['ohos.extra.param.key.form_identity']);
          let formName = String(want.parameters['ohos.extra.param.key.form_name']);
          let tempFlag = Boolean(want.parameters['ohos.extra.param.key.form_temporary']);
          // Persistently store widget data for subsequent use, such as instance acquisition and update.
          // Implement this API based on project requirements.
          hilog.info(domain, TAG, 'FormAbility onCreate' + formId);
          storeFormInfo(formId, formName, tempFlag, this.context);
        }
    
        // Called when the widget is created. The widget provider should return the widget data binding class.
        let obj: Record<string, string> = {
          'title': 'titleOnCreate',
          'detail': 'detailOnCreate'
        };
        let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
        return formData;
      },
      onCastToNormal(formId: string) {
        // Called when the widget host converts a temporary widget into a normal one. The widget provider should respond to the conversion. (Currently, there is no temporary widget scenario.)
        hilog.info(domain, TAG, 'FormAbility onCastToNormal');
      },
      onUpdate(formId: string) {
        // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
        hilog.info(domain, TAG, 'FormAbility onUpdate');
        let obj: Record<string, string> = {
          'title': 'titleOnUpdate',
          'detail': 'detailOnUpdate'
        };
        let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
        // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
        formProvider.updateForm(formId, formData).catch((error: Error) => {
          hilog.error(domain, TAG, 'FormAbility updateForm, error:' + JSON.stringify(error));
        });
      },
      onVisibilityChange(newStatus: Record<string, number>) {
        // 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.
        hilog.info(domain, TAG, 'FormAbility onVisibilityChange');
      },
      onEvent(formId: string, message: string) {
        // If the widget supports event triggering, override this method and implement the trigger.
        let obj: Record<string, string> = {
          'title': 'titleOnEvent',
          'detail': 'detailOnEvent'
        };
        let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
        // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
        formProvider.updateForm(formId, formData).catch((error: Error) => {
          hilog.error(domain, TAG, 'FormAbility updateForm, error:' + JSON.stringify(error));
        });
        hilog.info(domain, TAG, 'FormAbility onEvent');
      },
      onDestroy(formId: string) {
        // Delete widget data.
        hilog.info(domain, TAG, 'FormAbility onDestroy');
        // Delete the persistent widget instance data.
        // Implement this API based on project requirements.
        deleteFormInfo(formId, this.context);
      },
      onAcquireFormState(want: Want) {
        hilog.info(domain, TAG, 'FormAbility onAcquireFormState');
        return formInfo.FormState.READY;
      }
    };
    
    export default obj;

FormAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks.

[h2]Configuring the Widget Configuration File

The widget configuration file is named config.json. Find the config.json file for the widget and edit the file depending on your need.

[h2]Persistently Storing Widget Data

A 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. You should override onDestroy to implement widget data deletion.

const TAG: string = '[Sample_FAModelAbilityDevelop]';
const domain: number = 0xFF00;

const DATA_STORAGE_PATH: string = 'form_store';
let storeFormInfo = async (formId: string, formName: string, tempFlag: boolean, context: featureAbility.Context): Promise<void> => {
  // Only the widget name (formName) and whether it is a temporary widget (tempFlag) are persisted here.
  let formInfo: Record<string, string | number | boolean> = {
    'formName': formName,
    'tempFlag': tempFlag,
    'updateCount': 0
  };
  try {
    const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
    // Put the widget information.
    await storage.put(formId, JSON.stringify(formInfo));
    hilog.info(domain, TAG, `storeFormInfo, put form info successfully, formId: ${formId}`);
    await storage.flush();
  } catch (err) {
    hilog.error(domain, TAG, `failed to storeFormInfo, err: ${JSON.stringify(err as Error)}`);
  }
};

let deleteFormInfo = async (formId: string, context: featureAbility.Context) => {
  try {
    const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
    // Delete the widget information.
    await storage.delete(formId);
    hilog.info(domain, TAG, `deleteFormInfo, del form info successfully, formId: ${formId}`);
    await storage.flush();
  } catch (err) {
    hilog.error(domain, TAG, `failed to deleteFormInfo, err: ${JSON.stringify(err)}`);
  }
}

// ...
  onCreate(want: Want) {
    hilog.info(domain, TAG, 'FormAbility onCreate');
    if (want.parameters) {
      let formId = String(want.parameters['ohos.extra.param.key.form_identity']);
      let formName = String(want.parameters['ohos.extra.param.key.form_name']);
      let tempFlag = Boolean(want.parameters['ohos.extra.param.key.form_temporary']);
      // Persistently store widget data for subsequent use, such as instance acquisition and update.
      // Implement this API based on project requirements.
      hilog.info(domain, TAG, 'FormAbility onCreate' + formId);
      storeFormInfo(formId, formName, tempFlag, this.context);
    }

    // Called when the widget is created. The widget provider should return the widget data binding class.
    let obj: Record<string, string> = {
      'title': 'titleOnCreate',
      'detail': 'detailOnCreate'
    };
    let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
    return formData;
  },
// ...

let deleteFormInfo = async (formId: string, context: featureAbility.Context): Promise<void> => {
  try {
    const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
    // Delete the widget information.
    await storage.delete(formId);
    hilog.info(domain, TAG, `deleteFormInfo, del form info successfully, formId: ${formId}`);
    await storage.flush();
  } catch (err) {
    hilog.error(domain, TAG, `failed to deleteFormInfo, err: ${JSON.stringify(err)}`);
  }
};

// ...
    // Override onDestroy to implement widget data deletion.
  onDestroy(formId: string) {
    // Delete widget data.
    hilog.info(domain, TAG, 'FormAbility onDestroy');
    // Delete the persistent widget instance data.
    // Implement this API based on project requirements.
    deleteFormInfo(formId, this.context);
  }
// ...

For details about how to implement persistent data storage, see Application Data Persistence Overview.

The 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.

Converting a temporary widget to a normal one: After you swipe up on a widget application, a temporary widget is displayed. If you touch the pin button on the widget, it is displayed as a normal widget on the home screen.

Data 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.

[h2]Updating Widget Data

When an application initiates a scheduled or periodic update, the application obtains the latest data and calls updateForm() to update the widget.

const TAG: string = '[Sample_FAModelAbilityDevelop]';
const domain: number = 0xFF00;

onUpdate(formId: string) {
  // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
  hilog.info(domain, TAG, 'FormAbility onUpdate');
  let obj: Record<string, string> = {
    'title': 'titleOnUpdate',
    'detail': 'detailOnUpdate'
  };
  let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
  // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
  formProvider.updateForm(formId, formData).catch((error: Error) => {
    hilog.error(domain, TAG, 'FormAbility updateForm, error:' + JSON.stringify(error));
  });
}

[h2]Developing the Widget UI Page

You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. This section describes how to develop a page shown below.

In the FA model, only the JavaScript-based web-like development paradigm is supported when developing the widget UI.

[h2]Developing Widget Events

You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows:

  1. Set the onclick field in the HML file depending on the actions settings in the JSON file.

  2. Set the router event.

    • action: "router", which indicates a router event.

    • abilityName: name of the ability to redirect to (supports redirecting to the PageAbility component in the FA model and the UIAbility component in the Stage model). For example, the default UIAbility name created by DevEco Studio in the Stage model is com.example.entry.EntryAbility.

    • params: custom parameters passed to the target ability. Set them as needed. The values can be obtained from parameters in want when the target ability starts. For example, in the FA model, you can obtain want by calling featureAbility.getWant() in the PageAbility onCreate lifecycle, and then retrieve the configured parameters from its parameters field.

  3. Set the message event.

    • action: "message", which indicates a message event.

    • params: custom parameters of the message event. Set them as required. The value can be obtained from message in the widget lifecycle function onEvent.

The following is an example: