• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# In-Application Embedded Component (EmbeddedComponent)
2
3The **EmbeddedComponent** allows the current page to embed UI content provided by other EmbeddedUIExtensionAbilities within the same application. These UIs run in independent processes, offering enhanced security and stability.
4
5The **EmbeddedComponent** is primarily used for cross-module, cross-process embedded UI integration. Its core objective is to improve application flexibility and user experience through modular design.
6
7Be aware of the component's usage constraints and lifecycle management to maximize its benefits in application architecture.
8
9## Basic Concepts
10
11- [EmbeddedComponent](../reference/apis-arkui/arkui-ts/ts-container-embedded-component.md)
12
13  The **EmbeddedComponent** enables embedding UI content from another EmbeddedUIExtensionAbility within the same application. It supports modular development scenarios requiring process isolation, allowing flexible UI design by integrating specific functionalities or interfaces into another page.
14
15- [EmbeddedUIExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-embeddedUIExtensionAbility.md)
16
17  Defined and used in the provider application, the EmbeddedUIExtensionAbility enables cross-process UI embedding. It can only be launched by a UIAbility within the same application and requires multi-process permissions.
18
19## Constraints
20
21- Device Requirements
22
23  The **EmbeddedComponent** is supported only on devices configured with multi-process permissions.
24
25- Applicable Scope
26
27  The **EmbeddedComponent** can be used only in the UIAbility, and the EmbeddedUIExtensionAbility to start must belong to the same application as the UIAbility.
28
29- Attribute Restrictions
30
31  The **EmbeddedComponent** supports [universal attributes](../reference/apis-arkui/arkui-ts/ts-component-general-attributes.md), with default and minimum width and height values set to 10 vp.
32
33  The following width- and height-related attributes are not supported:
34  **constraintSize**, **aspectRatio**, **layoutWeight**, **flexBasis**, **flexGrow**, and **flexShrink**.
35
36- Event handling
37
38  Event information related to screen coordinates is converted based on the position, width, and height of the **EmbeddedComponent**, before being passed to the EmbeddedUIExtensionAbility for processing.
39
40  The **EmbeddedComponent** does not support universal events, including the [click event](../reference/apis-arkui/arkui-ts/ts-universal-events-click.md). It only supports the [onTerminated](../reference/apis-arkui/arkui-ts/ts-container-embedded-component.md#onterminated) and [onError](../reference/apis-arkui/arkui-ts/ts-container-embedded-component.md#onerror) events.
41
42## Scenario Example
43
44This example demonstrates the basic usage of the **EmbeddedComponent** and EmbeddedUIExtensionAbility.
45
46**Host Page**
47
48The host page is the parent page of the **EmbeddedComponent**, embedding and displaying the UI from the EmbeddedUIExtensionAbility. Below is a complete implementation:
49
50```ts
51import { Want } from '@kit.AbilityKit';
52
53@Entry
54@Component
55struct Index {
56  @State message: string = 'Message: '
57  private want: Want = {
58    bundleName: "com.example.embeddeddemo",
59    abilityName: "ExampleEmbeddedAbility",
60  }
61
62  build() {
63    Row() {
64      Column() {
65        Text(this.message).fontSize(30)
66        EmbeddedComponent(this.want, EmbeddedType.EMBEDDED_UI_EXTENSION)
67          .width('100%')
68          .height('90%')
69          .onTerminated((info) => {
70            // Triggered when the terminateSelfWithResult button is clicked on the extension page.
71            this.message = 'Termination: code = ' + info.code + ', want = ' + JSON.stringify(info.want);
72          })
73          .onError((error) => {
74            // Triggered on failure or exception.
75            this.message = 'Error: code = ' + error.code;
76          })
77      }
78      .width('100%')
79    }
80    .height('100%')
81  }
82}
83```
84
85In an ArkTS project, the implementation code for EmbeddedUIExtensionAbility is typically located in the **ets/extensionAbility** directory of the project. For example, the **ExampleEmbeddedAbility.ets** file is located in the **./ets/extensionAbility/** directory.
86
87Key considerations for implementing the host page:
88
89- Multi-process model check
90
91  Check whether the device has multi-process mode enabled during application startup. Provide clear error messages or guidance if it is disabled.
92
93- Exception handling
94
95  Use the [onError](../reference/apis-arkui/arkui-ts/ts-container-embedded-component.md#onerror) event to handle errors during embedded ability loading or execution.
96
97- Lifecycle management
98
99  Manage the lifecycle of the **EmbeddedComponent** to ensure proper resource cleanup.
100
101- Style configuration
102
103  Properly configure the size and position of the **EmbeddedComponent** to display embedded UIs as expected.
104
105**Provider Application Lifecycle Implementation**
106
107The provider application implements embedded UI extension abilities. Below is an example lifecycle implementation:
108
109```ts
110import { EmbeddedUIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit';
111
112const TAG: string = '[ExampleEmbeddedAbility]'
113
114export default class ExampleEmbeddedAbility extends EmbeddedUIExtensionAbility {
115  onCreate() {
116    console.log(TAG, `onCreate`);
117  }
118
119  onForeground() {
120    console.log(TAG, `onForeground`);
121  }
122
123  onBackground() {
124    console.log(TAG, `onBackground`);
125  }
126
127  onDestroy() {
128    console.log(TAG, `onDestroy`);
129  }
130
131  onSessionCreate(want: Want, session: UIExtensionContentSession) {
132    console.log(TAG, `onSessionCreate, want: ${JSON.stringify(want)}`);
133    let param: Record<string, UIExtensionContentSession> = {
134      'session': session
135    };
136    let storage: LocalStorage = new LocalStorage(param);
137    // Load the pages/extension.ets content.
138    session.loadContent('pages/extension', storage);
139  }
140
141  onSessionDestroy(session: UIExtensionContentSession) {
142    console.log(TAG, `onSessionDestroy`);
143  }
144}
145```
146
147Key implementation details:
148
149- Lifecycle stages
150
151  **onCreate** -> **onForeground**: from initialization to the visible state.
152
153  **onBackground** -> **onForeground**: state transition during foreground-background switching.
154
155  **onDestroy**: resource cleanup when the component is actively destroyed by the host.
156
157- Session management
158
159  **onSessionCreate**: creates an independent storage context and loads the UI.
160
161  **onSessionDestroy**: handles cleanup when the session ends.
162
163- Context passing
164
165  Use LocalStorage to pass the **UIExtensionContentSession** across components.
166
167  Bind ArkTS pages to extension ability contexts through **loadContent**.
168
169**Entry Page**
170
171The following is an implementation of the entry component of the provider application, which demonstrates how to use **UIExtensionContentSession** and how to exit the embedded page and return the result through a button click event. This code file needs to be declared in the **main_pages.json** configuration file.
172
173```ts
174import { UIExtensionContentSession } from '@kit.AbilityKit';
175
176let storage = new LocalStorage();
177
178@Entry(storage)
179@Component
180struct Extension {
181  @State message: string = 'EmbeddedUIExtensionAbility Index';
182  private session: UIExtensionContentSession | undefined = storage.get<UIExtensionContentSession>('session');
183
184  build() {
185    Column() {
186      Text(this.message)
187        .fontSize(20)
188        .fontWeight(FontWeight.Bold)
189      Button("terminateSelfWithResult").fontSize(20).onClick(() => {
190        // Call terminateSelfWithResult to exit when the button is clicked.
191        this.session?.terminateSelfWithResult({
192          resultCode: 1,
193          want: {
194            bundleName: "com.example.embeddeddemo",
195            abilityName: "ExampleEmbeddedAbility",
196          }
197        });
198      })
199    }.width('100%').height('100%')
200  }
201}
202```
203
204Key considerations for implementing the entry page:
205
2061. Session management
207
208  Properly obtain and use the **UIExtensionContentSession** instances to ensure communication with the host application.
209
2102. Result return
211
212  When returning results to the host through **terminateSelfWithResult**, specify:
213
214  - **resultCode**: result code.
215
216  - **want**: recipient of the result.
217
2183. Page lifecycle
219
220  Manage the lifecycle of the entry page to ensure proper resource cleanup.
221
2224. Style configuration
223
224  Properly configure page element styles to display the page as expected.
225
226**Configuration**
227
228  To enable embedded UI extension abilities, configure the application's configuration file.
229
230  Add the ExampleEmbeddedAbility configuration under the **extensionAbilities** tag in the **module.json5** file:
231
232```json
233{
234  "name": "ExampleEmbeddedAbility",
235  "srcEntry": "./ets/extensionAbility/ExampleEmbeddedAbility.ets",
236  "type": "embeddedUI"
237}
238```
239
240**Expected Results**
241
2421. An error message appears since multi-process mode is disabled by default.
243
244![en-us_image_0000001502261185](figures/en-us_image_0000001502261185.jpg)
245
2462. Use the following hdc command to enable multi-process mode. Then, restart the device:
247
248```bash
249hdc shell param set persist.sys.abilityms.multi_process_model true
250```
251
2523. The UI is displayed correctly after the application starts.
253
254![en-us_image_0000001502261065](figures/en-us_image_0000001502261065.jpg)
255
2564. Clicking the **terminateSelfWithResult** button hides the provider content and displays **onTerminated** information on the host page.
257