• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.app.ability.autoFillManager (autoFillManager)
2
3autoFillManager模块提供账号密码保存等功能。
4
5不同于页面切换时触发的系统自动保存功能,该功能需要由用户手动触发。例如用户在网站上输入了账号密码,并点击“保存”按钮,才能触发相应的自动保存操作。
6
7> **说明:**
8>
9> 本模块首批接口从API version 11 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
10>
11> 本模块接口仅可在Stage模型下使用。
12
13## 导入模块
14
15```ts
16import { autoFillManager } from '@kit.AbilityKit';
17```
18
19## AutoSaveCallback
20
21当保存请求完成时所触发的回调接口。
22
23### AutoSaveCallback.onSuccess
24
25onSuccess(): void
26
27当保存请求成功时,该回调被调用。
28
29**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
30
31**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
32
33**示例:**
34
35参见[AutoSaveCallback.onFailure](#autosavecallbackonfailure)。
36
37### AutoSaveCallback.onFailure
38
39onFailure(): void
40
41当保存请求失败时,该回调被调用。
42
43**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
44
45**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
46
47**示例:**
48
49  ```ts
50// Index.ets, 含有账号、密码框等组件的页面
51import { autoFillManager } from '@kit.AbilityKit';
52import { UIContext } from '@kit.ArkUI';
53import { BusinessError } from '@kit.BasicServicesKit';
54
55let uiContext = AppStorage.get<UIContext>("uiContext");
56let callback: autoFillManager.AutoSaveCallback = {
57  onSuccess: () => {
58    console.log("save request on success");
59  },
60  onFailure: () => {
61    console.log("save request on failure");
62  }
63};
64
65@Entry
66@Component
67struct Index {
68  build() {
69    Button('requestAutoSave')
70      .onClick(() => {
71        try {
72          // 发起保存请求
73          autoFillManager.requestAutoSave(uiContext, callback);
74        } catch (error) {
75          console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`);
76        }
77      })
78  }
79}
80  ```
81
82> **说明:**
83>
84> 示例中从AppStorage中取得的UiContext为预先在EntryAbility(拉起此页面的Ability)中OnWindowStageCreate生命周期获得,并存储到AppStorage中,具体可参考[requestAutoSave](#autofillmanagerrequestautosave)。
85
86## autoFillManager.requestAutoSave
87
88requestAutoSave(context: UIContext, callback?: AutoSaveCallback): void
89
90请求保存表单数据,使用callback异步回调。
91如果当前表单没有提供表单切换的功能,可以通过此接口保存历史表单输入数据,保存请求完成时会触发该回调。
92
93**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
94
95**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
96
97**参数:**
98
99| 参数名 | 类型 | 必填 | 说明 |
100| -------- | -------- | -------- | -------- |
101| context | [UIContext](../apis-arkui/js-apis-arkui-UIContext.md) | 是 | 将在其中执行保存操作的UI上下文。 |
102| callback | [AutoSaveCallback](#autosavecallback)  | 否 | 保存请求的回调函数。 |
103
104**错误码:**
105
106| 错误码ID | 错误信息 |
107| ------- | -------------------------------- |
108| 401      | The parameter check failed. Possible causes: 1. Get instance id failed; 2. Parse instance id failed; 3. The second parameter is not of type callback. |
109| 16000050 | Internal error. |
110
111以上错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
112
113**示例:**
114
115  ```ts
116// EntryAbility.ets
117import { UIAbility, common } from '@kit.AbilityKit';
118import { BusinessError } from '@kit.BasicServicesKit';
119import { window, UIContext } from '@kit.ArkUI';
120import { hilog } from '@kit.PerformanceAnalysisKit';
121
122export default class EntryAbility extends UIAbility {
123  onWindowStageCreate(windowStage: window.WindowStage): void {
124    // Main window is created, set main page for this ability
125    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
126    let localStorageData: Record<string, string | common.UIAbilityContext> = {
127      'message': "AutoFill Page",
128      'context': this.context,
129    };
130    let storage = new LocalStorage(localStorageData);
131    windowStage.loadContent('pages/Index', storage, (err, data) => {
132      if (err.code) {
133        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
134        return;
135      }
136      // Obtain the main window.
137      windowStage.getMainWindow((err: BusinessError, data: window.Window) => {
138        let errCode: number = err.code;
139        if (errCode) {
140          console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
141          return;
142        }
143        console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
144        // get UIContext instance.
145        let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
146        PersistentStorage.persistProp("uiContext", uiContext);
147      })
148      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
149    });
150  }
151}
152  ```
153
154  ```ts
155  // Index.ets
156import { autoFillManager } from '@kit.AbilityKit';
157import { UIContext } from '@kit.ArkUI';
158import { BusinessError } from '@kit.BasicServicesKit';
159
160@Entry
161@Component
162struct Index {
163  build() {
164    Row() {
165      Column() {
166        Text('Hello World')
167          .fontSize(50)
168          .fontWeight(FontWeight.Bold)
169      }
170
171      Button('requestAutoSave')
172        .onClick(() => {
173          let uiContext = AppStorage.get<UIContext>("uiContext");
174          console.log("uiContext: ", JSON.stringify(uiContext));
175          try {
176            // 发起保存请求
177            autoFillManager.requestAutoSave(uiContext, {
178              onSuccess: () => {
179                console.log("save request on success");
180              },
181              onFailure: () => {
182                console.log("save request on failure");
183              }
184            });
185          } catch (error) {
186            console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`);
187          }
188        })
189        .width('100%')
190    }
191    .height('100%')
192  }
193}
194  ```
195