• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.uiExtensionHost (System API)
2
3Intended only for the **UIExtensionComponent** that has process isolation requirements, the **uiExtensionHost** module provides APIs for obtaining the host application window information and information about the component itself.
4
5> **NOTE**
6>
7> No new function will be added to this module. Related functions will be provided in the [uiExtension](js-apis-arkui-uiExtension.md) interface.
8>
9> The initial APIs of this module are supported since API version 11. Updates will be marked with a superscript to indicate their earliest API version.
10>
11> The APIs provided by this module are system APIs.
12
13## Modules to Import
14
15```
16import { uiExtensionHost } from '@kit.ArkUI'
17```
18
19## UIExtensionHostWindowProxy
20
21### getWindowAvoidArea
22
23getWindowAvoidArea(type: window.AvoidAreaType): window.AvoidArea
24
25Obtains the area where this window cannot be displayed, for example, the system bar area, notch, gesture area, and soft keyboard area.
26
27**System capability**: SystemCapability.ArkUI.ArkUI.Full
28
29**System API**: This is a system API and cannot be called by third-party applications.
30
31| Name| Type| Mandatory| Description|
32| -------- | -------- | -------- | -------- |
33| type | [window.AvoidAreaType](js-apis-window.md#avoidareatype7) | Yes| Type of the area.|
34
35**Return value**
36
37| Type| Description|
38| -------- | -------- |
39| [window.AvoidArea](js-apis-window.md#avoidarea7) | Area where the window cannot be displayed.|
40
41**Return value**
42
43| ID| Error Message        |
44| -------- | ---------------- |
45| 401      | Parameter error. |
46
47**Example**
48
49```ts
50// ExtensionProvider.ts
51
52import { UIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
53import { window } from '@kit.ArkUI';
54
55export default class EntryAbility extends UIExtensionAbility {
56  onSessionCreate(want: Want, session: UIExtensionContentSession) {
57    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
58    // Obtain the information about the area where the window cannot be displayed.
59    const avoidArea = extensionHostWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
60    console.log(`avoidArea: ${JSON.stringify(avoidArea)}`);
61  }
62}
63```
64
65### on('avoidAreaChange')
66
67on(type: 'avoidAreaChange', callback: Callback<{ type: window.AvoidAreaType, area: window.AvoidArea }>): void
68
69Subscribes to the event indicating changes to the area where the window cannot be displayed.
70
71**System capability**: SystemCapability.ArkUI.ArkUI.Full
72
73**System API**: This is a system API and cannot be called by third-party applications.
74
75| Name  | Type  | Mandatory| Description                  |
76| -------- | ------ | ---- | ---------------------- |
77| type     | string | Yes  | Event type. The value is fixed at **'avoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.|
78| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback)<{ type: [window.AvoidAreaType](js-apis-window.md#avoidareatype7), area: [window.AvoidArea](js-apis-window.md#avoidarea7) }> | Yes| Callback used to return the area information. **type** indicates the type of the area where the window cannot be displayed, and **area** indicates the area.|
79
80**Error codes**
81
82| ID| Error Message                                                    |
83| -------- | ------------------------------------------------------------ |
84| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified.<br> 2. Incorrect parameters types.<br> 3. Parameter verification failed. |
85
86**Example**
87
88```ts
89// ExtensionProvider.ts
90import { UIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
91
92export default class EntryAbility extends UIExtensionAbility {
93  onSessionCreate(want: Want, session: UIExtensionContentSession) {
94    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
95    // Subscribe to the event indicating changes to the area where the window cannot be displayed.
96    extensionHostWindow.on('avoidAreaChange', (info) => {
97      console.info(`The avoid area of the host window is: ${JSON.stringify(info.area)}.`);
98    });
99  }
100}
101```
102
103### off('avoidAreaChange')
104
105off(type: 'avoidAreaChange', callback?: Callback<{ type: window.AvoidAreaType, area: window.AvoidArea }>): void
106
107Unsubscribes from the event indicating changes to the area where the window cannot be displayed.
108
109**System capability**: SystemCapability.ArkUI.ArkUI.Full
110
111**System API**: This is a system API and cannot be called by third-party applications.
112
113| Name  | Type  | Mandatory| Description                  |
114| -------- | ------ | ---- | ---------------------- |
115| type     | string | Yes  | Event type. The value is fixed at **'avoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.|
116| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback)<{ type: [window.AvoidAreaType](js-apis-window.md#avoidareatype7), area: [window.AvoidArea](js-apis-window.md#avoidarea7) }> | No| Callback used for unsubscription. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.|
117
118**Error codes**
119
120| ID| Error Message                                                    |
121| -------- | ------------------------------------------------------------ |
122| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified.<br> 2. Incorrect parameters types.<br> 3. Parameter verification failed. |
123
124**Example**
125
126```ts
127// ExtensionProvider.ts
128import { UIExtensionAbility, UIExtensionContentSession} from '@kit.AbilityKit';
129
130export default class EntryAbility extends UIExtensionAbility {
131  onSessionDestroy(session: UIExtensionContentSession) {
132    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
133    // Cancel all subscriptions to the event indicating changes to the area where the window cannot be displayed.
134    extensionHostWindow.off('avoidAreaChange');
135  }
136}
137```
138
139### on('windowSizeChange')
140
141on(type: 'windowSizeChange', callback: Callback<window.Size>): void
142
143Subscribes to the window size change event.
144
145**System capability**: SystemCapability.ArkUI.ArkUI.Full
146
147**System API**: This is a system API and cannot be called by third-party applications.
148
149| Name  | Type                 | Mandatory| Description                  |
150| -------- | --------------------- | ---- | ---------------------- |
151| type     | string                | Yes  | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.|
152| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback)<[window.Size](js-apis-window.md#size7)> | Yes  | Callback used to return the window size.|
153
154**Error codes**
155
156| ID| Error Message                                                    |
157| -------- | ------------------------------------------------------------ |
158| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified.<br> 2. Incorrect parameters types.<br> 3. Parameter verification failed. |
159
160**Example**
161
162```ts
163// ExtensionProvider.ts
164import { UIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
165
166export default class EntryAbility extends UIExtensionAbility {
167  onSessionCreate(want: Want, session: UIExtensionContentSession) {
168    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
169    // Subscribe to the window size change event of the host application.
170    extensionHostWindow.on('windowSizeChange', (size) => {
171      console.info(`The avoid area of the host window is: ${JSON.stringify(size)}.`);
172    });
173  }
174}
175```
176
177### off('windowSizeChange')
178
179off(type: 'windowSizeChange', callback?: Callback<window.Size>): void
180
181Unsubscribes from the window size change event.
182
183**System capability**: SystemCapability.ArkUI.ArkUI.Full
184
185**System API**: This is a system API and cannot be called by third-party applications.
186
187| Name  | Type                 | Mandatory| Description                  |
188| -------- | --------------------- | ---- | ---------------------- |
189| type     | string                | Yes  | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.|
190| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback)<[window.Size](js-apis-window.md#size7)> | No  | Callback used for unsubscription. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.|
191
192**Error codes**
193
194| ID| Error Message                                                    |
195| -------- | ------------------------------------------------------------ |
196| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified.<br> 2. Incorrect parameters types.<br> 3. Parameter verification failed. |
197
198**Example**
199
200```ts
201// ExtensionProvider.ts
202import { UIExtensionAbility, UIExtensionContentSession } from '@kit.AbilityKit';
203
204export default class EntryAbility extends UIExtensionAbility {
205  onSessionDestroy(session: UIExtensionContentSession) {
206    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
207    // Unsubscribe from the window size change event of the host application.
208    extensionHostWindow.off('windowSizeChange');
209  }
210}
211```
212
213### properties
214
215properties: UIExtensionHostWindowProxyProperties
216
217Provides the information about the host application window and the **UIExtensionComponent**.
218
219**System capability**: SystemCapability.ArkUI.ArkUI.Full
220
221**System API**: This is a system API and cannot be called by third-party applications.
222
223| Name    | Type                                | Description                            |
224| ---------- | ------------------------------------ | -------------------------------- |
225| properties | [UIExtensionHostWindowProxyProperties](#uiextensionhostwindowproxyproperties) | Information about the host application window and the **UIExtensionComponent**.|
226
227**Example**
228
229```ts
230// ExtensionProvider.ts
231import { UIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
232
233export default class EntryAbility extends UIExtensionAbility {
234  onSessionCreate(want: Want, session: UIExtensionContentSession) {
235    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
236    // Obtain the position and size of the <UIExtensionComponent>.
237    const rect = extensionHostWindow.properties.uiExtensionHostWindowProxyRect;
238    console.log(`Rect Info: ${JSON.stringify(rect)}`);
239  }
240}
241```
242
243### hideNonSecureWindows
244
245hideNonSecureWindows(shouldHide: boolean): Promise&lt;void&gt;
246
247Sets whether to hide insecure windows.
248> **NOTE**
249>
250> Insecure windows refer to the windows that may block the **UIExtensionComponent**, such as global floating windows, host subwindows, and dialog box windows created by the host application, excluding the aforementioned types of windows created by system applications. When the **UIExtensionComponent** is used to present important information, you can hide insecure windows to prevent such information from being obscured. When the **UIExtensionComponent** is not displayed or is destroyed, you must unhide the insecure windows. By default, the **UIExtensionComponent** created using the **CreateModalUIExtension** API hides insecure windows. To cancel this behavior and show insecure windows, apply for the **ohos.permission.ALLOW_SHOW_NON_SECURE_WINDOWS** permission and call this API to set **shouldHide** to **false**.
251
252**System capability**: SystemCapability.ArkUI.ArkUI.Full
253
254**System API**: This is a system API and cannot be called by third-party applications.
255
256**Parameters**
257
258| Name     | Type                     | Mandatory| Description      |
259| ----------- | ------------------------- | ---- | ---------- |
260| shouldHide  | boolean                   | Yes  | Whether to hide insecure windows. The value **true** means to hide insecure windows, and **false** means the opposite.|
261
262**Return value**
263
264| Type               | Description                     |
265| ------------------- | ------------------------- |
266| Promise&lt;void&gt; | Promise that returns no value.|
267
268**Error codes**
269
270| ID| Error Message                                                    |
271| -------- | ------------------------------------------------------------ |
272| 202      | Permission verification failed. A non-system application calls a system API. |
273| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameters types. <br> 3. Parameter verification failed. |
274| 1300002  | Abnormal state. Possible causes: <br> 1. Permission denied. Interface caller does not have permission "ohos.permission.ALLOW_SHOW_NON_SECURE_WINDOWS". <br> 2. The UIExtension window proxy is abnormal. |
275| 1300003  | This window manager service works abnormally. |
276
277**Example**
278
279```ts
280// ExtensionProvider.ts
281
282import { UIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
283import { BusinessError } from '@kit.BasicServicesKit';
284
285export default class EntryAbility extends UIExtensionAbility {
286  onSessionCreate(want: Want, session: UIExtensionContentSession) {
287    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
288    // Hide insecure windows.
289    extensionHostWindow.hideNonSecureWindows(true).then(()=> {
290      console.log(`Succeeded in hiding the non-secure windows.`);
291    }).catch((err: BusinessError)=> {
292      console.log(`Failed to hide the non-secure windows. Cause:${JSON.stringify(err)}`);
293    })
294  }
295  onSessionDestroy(session: UIExtensionContentSession) {
296    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
297    // Unhide insecure windows.
298    extensionHostWindow.hideNonSecureWindows(false).then(()=> {
299      console.log(`Succeeded in showing the non-secure windows.`);
300    }).catch((err: BusinessError)=> {
301      console.log(`Failed to show the non-secure windows. Cause:${JSON.stringify(err)}`);
302    })
303  }
304}
305```
306
307### createSubWindowWithOptions<sup>12+</sup>
308
309createSubWindowWithOptions(name: string, subWindowOptions: window.SubWindowOptions): Promise&lt;window.Window&gt;
310
311Creates a subwindow for this **UIExtensionHostWindowProxy** instance. This API uses a promise to return the result.
312
313**System capability**: SystemCapability.ArkUI.ArkUI.Full
314
315**System API**: This is a system API and cannot be called by third-party applications.
316
317**Model restriction**: This API can be used only in the stage model.
318
319**Parameters**
320
321| Name| Type  | Mandatory| Description          |
322| ------ | ------ | ---- | -------------- |
323| name   | string | Yes  | Name of the subwindow.|
324| subWindowOptions | [window.SubWindowOptions](js-apis-window.md#subwindowoptions11) | Yes| Parameters used for creating the subwindow.|
325
326**Return value**
327
328| Type                            | Description                                            |
329| -------------------------------- | ------------------------------------------------ |
330| Promise&lt;[window.Window](js-apis-window.md#window)&gt; | Promise used to return the subwindow created.|
331
332**Error codes**
333
334For details about the error codes, see [Window Error Codes](errorcode-window.md).
335
336| ID| Error Message|
337| ------- | ------------------------------ |
338| 401 | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified.<br> 2. Incorrect parameters types.<br> 3. Parameter verification failed. |
339| 801 | Capability not supported on this device. |
340| 1300002 | This window state is abnormal. |
341| 1300005 | This window proxy is abnormal. |
342
343**Example:**
344
345```ts
346// ExtensionProvider.ts
347import { UIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
348import { BusinessError } from '@kit.BasicServicesKit';
349import { window } from '@kit.ArkUI';
350
351export default class EntryAbility extends UIExtensionAbility {
352  onSessionCreate(want: Want, session: UIExtensionContentSession) {
353    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
354    const subWindowOpts: window.SubWindowOptions = {
355      title: 'This is a subwindow',
356      decorEnabled: true
357    };
358    // Create a subwindow.
359    extensionHostWindow.createSubWindowWithOptions('subWindowForHost', subWindowOpts)
360      .then((subWindow: window.Window) => {
361        subWindow.loadContent('pages/Index', (err, data) =>{
362          if (err && err.code != 0) {
363            return;
364          }
365          subWindow?.resize(300, 300, (err, data)=>{
366            if (err && err.code != 0) {
367              return;
368            }
369            subWindow?.moveWindowTo(100, 100, (err, data)=>{
370              if (err && err.code != 0) {
371                return;
372              }
373              subWindow?.showWindow((err, data) => {
374                if (err && err.code == 0) {
375                  console.info(`The subwindow has been shown!`);
376                } else {
377                  console.error(`Failed to show the subwindow!`);
378                }
379              });
380            });
381          });
382        });
383      }).catch((error: BusinessError) => {
384        console.error(`Create subwindow failed: ${JSON.stringify(error)}`);
385      })
386  }
387}
388```
389
390### setWaterMarkFlag<sup>12+</sup>
391
392setWaterMarkFlag(enable: boolean): Promise&lt;void&gt;
393
394Adds or deletes the watermark flag for this window. This API uses a promise to return the result.
395> **NOTE**
396>
397> With the watermark flag added, the watermark is applied on the full screen when the window is in the foreground, regardless of whether the window is displayed in full screen, floating, and split screen mode.
398
399**System capability**: SystemCapability.ArkUI.ArkUI.Full
400
401**System API**: This is a system API and cannot be called by third-party applications.
402
403**Parameters**
404
405| Name| Type    | Mandatory| Description                                           |
406| ------ | ------- | --- | ------------------------------------------------ |
407| enable | boolean | Yes  | Whether to add or delete the flag. The value **true** means to add the watermark flag, and **false** means to delete the watermark flag.|
408
409**Return value**
410
411| Type               | Description                     |
412| ------------------- | ------------------------- |
413| Promise&lt;void&gt; | Promise that returns no value.|
414
415**Error codes**
416
417| ID| Error Message|
418| ------- | ---------------------------------------------- |
419| 1300002 | This window state is abnormal.                 |
420| 1300003 | This window manager service works abnormally.  |
421| 1300008 | The operation is on invalid display. |
422
423**Example**
424
425```ts
426// ExtensionProvider.ts
427import { UIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
428import { BusinessError } from '@kit.BasicServicesKit';
429
430export default class EntryAbility extends UIExtensionAbility {
431  onSessionCreate(want: Want, session: UIExtensionContentSession) {
432    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
433    // Add the watermark flag.
434    extensionHostWindow.setWaterMarkFlag(true).then(() => {
435      console.log(`Succeeded in setting water mark flag of window.`);
436    }).catch((err: BusinessError) => {
437      console.log(`Failed to setting water mark flag of window. Cause:${JSON.stringify(err)}`);
438    })
439  }
440  onSessionDestroy(session: UIExtensionContentSession) {
441    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
442    // Delete the watermark flag.
443    extensionHostWindow.setWaterMarkFlag(false).then(() => {
444      console.log(`Succeeded in deleting water mark flag of window.`);
445    }).catch((err: BusinessError) => {
446      console.log(`Failed to deleting water mark flag of window. Cause:${JSON.stringify(err)}`);
447    })
448  }
449}
450```
451### hidePrivacyContentForHost<sup>13+</sup>
452
453hidePrivacyContentForHost(shouldHide: boolean): Promise&lt;void&gt;
454
455Sets whether to enable privacy protection for the UIExtension component during non-system screenshots. This API uses a promise to return the result.
456> **NOTE**
457>
458> When privacy protection is enabled, using [window.snapshot](js-apis-window.md#snapshot9) or [UIContext.getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12) will not capture the content of the current component (excluding child windows created under this component).
459
460
461**System capability**: SystemCapability.ArkUI.ArkUI.Full
462
463**System API**: This is a system API and cannot be called by third-party applications.
464
465**Parameters**
466
467| Name| Type    | Mandatory| Description                                           |
468| ------ | ------- | --- | ------------------------------------------------ |
469| shouldHide | boolean | Yes  | Whether to enable privacy protection for screenshots. The value **true** means to enable privacy protection for screenshots, and **false** means the opposite.|
470
471**Return value**
472
473| Type               | Description                     |
474| ------------------- | ------------------------- |
475| Promise&lt;void&gt; | Promise that returns no value.|
476
477**Error codes**
478
479For details about the error codes, see [Window Error Codes](errorcode-window.md).
480
481| ID| Error Message                                                    |
482| -------- | ------------------------------------------------------------ |
483| 202      | Permission verification failed. A non-system application calls a system API. |
484| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameters types. <br> 3. Parameter verification failed. |
485| 1300002  | The UIExtension window proxy is abnormal.                    |
486
487**Example**
488
489```ts
490// ExtensionProvider.ts
491import { UIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
492import { BusinessError } from '@kit.BasicServicesKit';
493
494export default class EntryAbility extends UIExtensionAbility {
495  onSessionCreate(want: Want, session: UIExtensionContentSession) {
496    const extensionHostWindow = session.getUIExtensionHostWindowProxy();
497    // Enable privacy protection for screenshots.
498    extensionHostWindow.hidePrivacyContentForHost(true).then(() => {
499      console.log(`Successfully enabled privacy protection for non-system screenshots.`);
500    }).catch((err: BusinessError) => {
501      console.log(`Failed enabled privacy protection for non-system screenshots. Cause:${JSON.stringify(err)}`);
502    })
503  }
504}
505```
506
507## UIExtensionHostWindowProxyProperties
508
509Defines information about the host application window and **UIExtensionComponent**.
510
511**System capability**: SystemCapability.ArkUI.ArkUI.Full
512
513**System API**: This is a system API.
514
515| Name                        | Type       | Mandatory     | Description                            |
516| ------------------------------ | ----------- | -------------------------------- | -------------------------------- |
517| uiExtensionHostWindowProxyRect | [window.Rect](js-apis-window.md#rect7) | Yes| Position, width, and height of the **UIExtensionComponent**.|
518
519## Example
520
521This example shows how to use all the available APIs in the UIExtensionAbility. The bundle name of the sample application, which requires a system signature, is **com.example.uiextensiondemo**, and the UIExtensionAbility to start is **ExampleUIExtensionAbility**.
522
523- The EntryAbility (UIAbility) of the sample application loads the **pages/Index.ets** file, whose content is as follows:
524
525  ```ts
526  // The UIAbility loads pages/Index.ets when started.
527  import { Want } from '@kit.AbilityKit';
528
529  @Entry
530  @Component
531  struct Index {
532    @State message: string = 'Message: '
533    private want: Want = {
534      bundleName: "com.example.uiextensiondemo",
535      abilityName: "ExampleUIExtensionAbility",
536      parameters: {
537        "ability.want.params.uiExtensionType": "sys/commonUI"
538      }
539    }
540
541    build() {
542      Row() {
543        Column() {
544          Text(this.message).fontSize(30)
545          UIExtensionComponent(this.want)
546            .width('100%')
547            .height('90%')
548        }
549        .width('100%')
550      }
551      .height('100%')
552    }
553  }
554  ```
555
556- The UIExtensionAbility to start by the **UIExtensionComponent** is implemented in the **ets/extensionAbility/ExampleUIExtensionAbility** file. The file content is as follows:
557
558  ```ts
559  import { UIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
560
561  const TAG: string = '[ExampleUIExtensionAbility]'
562  export default class ExampleUIExtensionAbility extends UIExtensionAbility {
563    onCreate() {
564      console.log(TAG, `onCreate`);
565    }
566
567    onForeground() {
568      console.log(TAG, `onForeground`);
569    }
570
571    onBackground() {
572      console.log(TAG, `onBackground`);
573    }
574
575    onDestroy() {
576      console.log(TAG, `onDestroy`);
577    }
578
579    onSessionCreate(want: Want, session: UIExtensionContentSession) {
580      console.log(TAG, `onSessionCreate, want: ${JSON.stringify(want)}`);
581      let param: Record<string, UIExtensionContentSession> = {
582        'session': session
583      };
584      let storage: LocalStorage = new LocalStorage(param);
585      session.loadContent('pages/extension', storage);
586    }
587  }
588  ```
589
590- The entry page file of the UIExtensionAbility is **pages/extension.ets**, whose content is as follows:
591
592  ```ts
593  import { UIExtensionContentSession } from '@kit.AbilityKit';
594  import { BusinessError } from '@kit.BasicServicesKit';
595  import { uiExtensionHost, window } from '@kit.ArkUI';
596
597  let storage = LocalStorage.getShared()
598
599  @Entry(storage)
600  @Component
601  struct Extension {
602    @State message: string = 'UIExtensionAbility Index';
603    private session: UIExtensionContentSession | undefined = storage.get<UIExtensionContentSession>('session');
604    private extensionWindow: uiExtensionHost.UIExtensionHostWindowProxy | undefined = this.session?.getUIExtensionHostWindowProxy();
605    private subWindow: window.Window | undefined = undefined;
606
607    aboutToAppear(): void {
608      this.extensionWindow?.on('windowSizeChange', (size) => {
609          console.info(`size = ${JSON.stringify(size)}`);
610      });
611      this.extensionWindow?.on('avoidAreaChange', (info) => {
612          console.info(`type = ${JSON.stringify(info.type)}, area = ${JSON.stringify(info.area)}`);
613      });
614      let promise = this.extensionWindow?.hideNonSecureWindows(true);
615      promise?.then(()=> {
616        console.log(`Succeeded in hiding the non-secure windows.`);
617      }).catch((err: BusinessError)=> {
618        console.log(`Failed to hide the non-secure windows. Cause:${JSON.stringify(err)}`);
619      })
620      extensionHostWindow.hidePrivacyContentForHost(true).then(() => {
621        console.log(`Successfully enabled privacy protection for non-system screenshots.`);
622      }).catch((err: BusinessError) => {
623        console.log(`Failed enabled privacy protection for non-system screenshots. Cause:${JSON.stringify(err)}`);
624      })
625    }
626
627    aboutToDisappear(): void {
628      this.extensionWindow?.off('windowSizeChange');
629      this.extensionWindow?.off('avoidAreaChange');
630      let promise = this.extensionWindow?.hideNonSecureWindows(false);
631      promise?.then(()=> {
632        console.log(`Succeeded in showing the non-secure windows.`);
633      }).catch((err: BusinessError)=> {
634        console.log(`Failed to show the non-secure windows. Cause:${JSON.stringify(err)}`);
635      })
636    }
637
638    build() {
639      Column() {
640        Text(this.message)
641          .fontSize(20)
642          .fontWeight(FontWeight.Bold)
643        Button("Obtain Component Size").width('90%').margin({top: 5, bottom: 5}).fontSize(16).onClick(() => {
644          let rect = this.extensionWindow?.properties.uiExtensionHostWindowProxyRect;
645          console.info(`Width, height, and position of the UIExtensionComponent: ${JSON.stringify(rect)}`);
646        })
647        Button("Obtain Avoid Area Info").width('90%').margin({top: 5, bottom: 5}).fontSize(16).onClick(() => {
648          let avoidArea: window.AvoidArea | undefined = this.extensionWindow?.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
649          console.info(`System avoid area: ${JSON.stringify(avoidArea)}`);
650        })
651        Button("Create Subwindow").width('90%').margin({top: 5, bottom: 5}).fontSize(16).onClick(() => {
652          let subWindowOpts: window.SubWindowOptions = {
653            'title': 'This is a subwindow',
654            decorEnabled: true
655          };
656          this.extensionWindow?.createSubWindowWithOptions('subWindowForHost', subWindowOpts)
657            .then((subWindow: window.Window) => {
658              this.subWindow = subWindow;
659              this.subWindow.loadContent('pages/Index', storage, (err, data) =>{
660                if (err && err.code != 0) {
661                  return;
662                }
663                this.subWindow?.resize(300, 300, (err, data)=>{
664                  if (err && err.code != 0) {
665                    return;
666                  }
667                  this.subWindow?.moveWindowTo(100, 100, (err, data)=>{
668                    if (err && err.code != 0) {
669                      return;
670                    }
671                    this.subWindow?.showWindow((err, data) => {
672                      if (err && err.code == 0) {
673                        console.info(`The subwindow has been shown!`);
674                      } else {
675                        console.error(`Failed to show the subwindow!`);
676                      }
677                    });
678                  });
679                });
680              });
681            }).catch((error: BusinessError) => {
682              console.error(`Create subwindow failed: ${JSON.stringify(error)}`);
683            })
684        })
685      }.width('100%').height('100%')
686    }
687  }
688  ```
689
690- Add an item to **extensionAbilities** in the **module.json5** file of the sample application. The details are as follows:
691  ```json
692  {
693    "name": "ExampleUIExtensionAbility",
694    "srcEntry": "./ets/extensionAbility/ExampleUIExtensionAbility.ets",
695    "type": "sys/commonUI",
696  }
697  ```
698