• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# IsolatedComponent (System API)
2
3**IsolatedComponent** is designed to support the embedding and display of UIs provided by independent .abc files within the current page, with the displayed content running in a restricted worker thread.
4
5The **FolderStack** component is usually used in modular development scenarios where .abc file hot update is required.
6
7> **NOTE**
8>
9> This component is supported since API version 12. 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## Constraints
14
15**Specifications Constraints**
16
171. This component does not support preview.
18
192. .abc files must pass the [VerifyAbc](../../apis-ability-kit/js-apis-bundleManager-sys.md#bundlemanagerverifyabc11) verification to be used in this component.
20
213. Construction parameter updates are not supported; only the initial input is effective.
22
234. Nesting of **IsolatedComponent** components is not supported.
24
25**Experience Constraints**
26
271. When an **IsolatedComponent** component is created, there is a certain amount of time required for the restricted worker thread to load and render the .abc file layout. During this period, the background color of the **IsolatedComponent** is displayed.
28
292. The main thread and the restricted worker thread handle layout rendering asynchronously, which can lead to desynchronization in page changes caused by layout alterations or rotations.
30
313. Event transmission between the main thread and the restricted worker thread is managed asynchronously, and there is no support for event bubbling between threads. As a result, UI interactions between threads may encounter event conflicts.
32
33**Security Constraints**
34
351. Displaying an independent .abc file through the **IsolatedComponent** component in the host process means that the .abc file content is fully accessible to the host, granting the host the control over the file content. For security-sensitive situations where such open access could be a risk, the use of this feature is disabled.
36
372. Running independent .abc files in a restricted worker thread offers a level of security, as the .abc file content is isolated and does not interfere with the main thread.
38
39## Child Components
40
41Not supported
42
43## APIs
44
45IsolatedComponent(options: IsolatedOptions)
46
47Creates an **IsolatedComponent** component to display the .abc file executed in a restricted worker thread.
48
49**Parameters**
50
51| Name               | Type                                                  | Mandatory| Description          |
52| --------------------- | ---------------------------------------------------------- | ---- | ------------------ |
53| options | [IsolatedOptions](#isolatedoptions)                | Yes  | Construction parameters.|
54
55## IsolatedOptions
56Describes the optional construction parameters during **IsolatedComponent** construction.
57
58**Parameters**
59
60| Name              | Type                                | Mandatory| Description                                                                                                     |
61| ----                 | ---------------------------------------- | ---- | ---------------                                                                                               |
62| want | [Want](../../apis-ability-kit/js-apis-app-ability-want.md)                                  | Yes  | .abc file information to load.|
63| worker | [RestrictedWorker](../../apis-arkts/js-apis-worker-sys.md#restrictedworker11)       | Yes  | Restricted worker thread where the .abc file is running.|
64
65## Attributes
66Only the [width](ts-universal-attributes-size.md#width), [height](ts-universal-attributes-size.md#height), and [backgroundColor](ts-universal-attributes-background.md#backgroundcolor) universal attributes are supported.
67
68## Events
69
70The [universal events](ts-component-general-events.md) are not supported.
71
72Events are asynchronously passed to the restricted worker thread after coordinate conversion.
73
74The following events are supported:
75
76### onError
77
78onError(callback:ErrorCallback)
79
80Invoked when an error occurs during the running of the **IsolatedComponent**. You can obtain the error information based on the **code**, **name**, and **message** parameters in the callback and rectify the exception accordingly.
81
82**Parameters**
83
84| Name                      | Type  | Description                                                        |
85| ---------------------------- | ------ | ------------------------------------------------------------ |
86| callback                        | [ErrorCallback](../../apis-basic-services-kit/js-apis-base.md#errorcallback) | Error information.   |
87
88## Example: Loading an IsolatedComponent
89
90This example demonstrates the basic usage of the **IsolatedComponent** component. The sample application's **bundleName** is **"com.example.isolateddemo"**, and the component uses the .abc file and an extension page from the same application as the embedded content. The specific testing steps after building the application project are as follows:
911. Build the HAP in DevEco Studio and install it on the device.
922. Upload the generated **modules.abc** file to the application sandbox path** /data/app/el2/100/base/com.example.isolateddemo/haps/entry/files** using DevEco Studio or the [hdc](../../../dfx/hdc.md) tool.
933. Open the application page and click the **verifyAbc** button to verify the .abc file, which logs "VerifyAbc successfully."
944. Click the **showIsolatedComponent** button to display the **IsolatedComponent** with the content "Hello World."
95
96- Restricted Worker thread script **ets/workers/OhCardWorker.ets**:
97  ```ts
98  // OhCardWorker.ets
99  import { worker, ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@kit.ArkTS';
100  const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
101
102  workerPort.onmessage = (e: MessageEvents) => {}
103  workerPort.onmessageerror = (e: MessageEvents) => {}
104  workerPort.onerror = (e: ErrorEvent) => {}
105  ```
106
107- Home page (**ets/pages/Index.ets**) loaded by the entry ability (**EntryAbility**):
108  ```ts
109  import { worker } from '@kit.ArkTS';
110  import { bundleManager } from '@kit.AbilityKit';
111  import { BusinessError } from '@kit.BasicServicesKit';
112
113  // Verify the .abc file and copy it to the specified sandbox path.
114  function VerifyAbc(abcPaths: Array<string>, deleteOriginalFiles: boolean) {
115    try {
116      bundleManager.verifyAbc(abcPaths, deleteOriginalFiles, (err) => {
117        if (err) {
118          console.error("VerifyAbc failed, error message: " + err.message);
119        } else {
120          console.info("VerifyAbc successfully.");
121        }
122      });
123    } catch (err) {
124      let message = (err as BusinessError).message;
125      console.error("VerifyAbc failed, error message: " + message);
126    }
127  }
128
129  @Entry
130  @Component
131  struct Index {
132    @State isShow: boolean = false;
133    @State resourcePath: string = "";
134    @State abcPath: string = "";
135    @State entryPoint: string = "";
136    // .abc file name
137    private fileName: string = "modules";
138    // Bundle name of the application to which the .abc file belongs
139    private bundleName: string = "com.example.isolateddemo";
140    // Restricted Worker thread
141    private worker ?: worker.RestrictedWorker = new worker.RestrictedWorker("entry/ets/workers/OhCardWorker.ets");
142
143    build() {
144      Row() {
145        Column() {
146          // 1. Verify the .abc file.
147          Button("verifyAbc").onClick(() => {
148            let abcFilePath = `${getContext(this).filesDir}/${this.fileName}.abc`;
149            console.log("abcFilePath: " + abcFilePath);
150            VerifyAbc([abcFilePath], false);
151          }).height(100).width(100)
152
153          // 2. Display the IsolatedComponent.
154          Button("showIsolatedComponent").onClick(() => {
155            if (!this.isShow) {
156              // Resource path
157              this.resourcePath = `${getContext(this).filesDir}/${this.fileName}.hap`;
158              // Sandbox path after the .abc file is verified
159              this.abcPath = `/abcs${getContext(this).filesDir}/${this.fileName}`;
160              // Entry to the page to be displayed
161              this.entryPoint = `${this.bundleName}/entry/ets/pages/extension`;
162              this.isShow = true;
163            }
164          }).height(100).width(100)
165
166          if (this.isShow) {
167            IsolatedComponent({
168              want: {
169                "parameters": {
170                  "resourcePath": this.resourcePath,
171                  "abcPath": this.abcPath,
172                  "entryPoint": this.entryPoint
173                }
174              },
175              worker: this.worker
176            })
177              .width(300)
178              .height(300)
179              .onError((err) => {
180                console.info("onError : " + JSON.stringify(err));
181              })
182          }
183        }
184        .width('100%')
185      }
186      .height('100%')
187    }
188  }
189  ```
190
191- The entry page file **ets/pages/extension.ets**, which runs in a restricted Worker thread, needs to be configured in the **resources/base/profile/main_pages.json** file with the following content:
192  ```ts
193  @Entry
194  @Component
195  struct Extension {
196    @State message: string = 'Hello World';
197
198    build() {
199      RelativeContainer() {
200        Text(this.message)
201          .id('HelloWorld')
202          .fontSize(50)
203          .fontWeight(FontWeight.Bold)
204          .alignRules({
205            center: { anchor: '__container__', align: VerticalAlign.Center },
206            middle: { anchor: '__container__', align: HorizontalAlign.Center }
207          })
208      }
209      .height('100%')
210      .width('100%')
211    }
212  }
213  ```
214
215- Add the **requestPermissions** tag in the **module.json5** configuration file to allow the execution of dynamically distributed Ark bytecode in restricted mode:
216  ```json
217  "requestPermissions": [
218    {
219      "name": "ohos.permission.RUN_DYN_CODE",
220      "usedScene": {
221        "abilities": [
222          "EntryAbility"
223        ],
224        "when": "inuse"
225      }
226    }
227  ]
228  ```
229