• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# PluginComponent
2
3The **\<PluginComponent>** allows the UI provided by an external application to be displayed in the application. To implement the update through inter-process communication (IPC), see [@ohos.pluginComponent](../apis/js-apis-plugincomponent.md).
4
5
6>  **NOTE**
7>
8>  - This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
9>  - The APIs provided by this component are system APIs.
10
11## Child Components
12
13Not supported
14
15
16## APIs
17
18PluginComponent(value: { template: PluginComponentTemplate, data: KVObject})
19
20Creates a **PluginComponent** to display the UI provided by an external application.
21
22**Parameters**
23
24| Name| Type                                                                                                                                                       | Mandatory| Description                                                                                                 |
25| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------------------------------------------------------------- |
26| value  | {<br>template:  [PluginComponentTemplate](#plugincomponenttemplate),<br>data: [KVObject](../apis/js-apis-plugincomponent.md#kvobject)<br>} | Yes  | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.<br>**data**: data passed to the **PluginComponent** provider.|
27
28## PluginComponentTemplate
29
30| Name      | Type  | Description                       |
31| ---------- | ------ | --------------------------- |
32| source     | string | Component template name.               |
33| bundleName | string | Bundle name of the provider ability.|
34## Attributes
35The [universal attributes](ts-universal-attributes-size.md) are supported, and **size** must be set.
36
37**NOTE**
38
39The template can be provided in either of the following modes:
40* Use an absolute path. In this case, set **source** to the absolute path of the template and leave **bundleName** blank. This mode is not recommended as it is applicable only to standalone templates that do not need to load resources.
41* Use an application package. In this case, set **bundleName** to the application bundle name and **source** to the relative path of the HAP file template. In the multi-HAP scenario, a HAP file is identified based on its relative path and name.
42
43  Example: **{source: 'ets/pages/plugin.js&plugin', bundleName:'com.example.provider'}**
44
45  The template is provided only when **source** can be set to an ability name in the FA model.
46
47  Example: **{source:'plugin', bundleName:'com.example.provider'}**
48
49
50## Events
51
52Only the [gesture event](ts-gesture-settings.md) can be distributed to the provider page and processed inside the provider page.
53
54In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
55
56| Name                                                                                                               | Description                                                              |
57| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
58| onComplete(callback: () =&gt; void)                                                                  | Triggered when the component loading is complete.                                                    |
59| onError(callback: (info: { errcode: number, msg: string }) =&gt; void) | Triggered when an error occurs during component loading.<br>**errcode**: error code.<br>**msg**: error information.|
60
61## Example
62
63
64### PluginComponent User
65
66```ts
67//PluginUserExample.ets
68import plugin from "./plugin_component"
69class source2BundleName {
70  source: string = ""
71  bundleName: string = ""
72}
73interface Info{
74  errcode:number,
75  msg:string
76}
77@Entry
78@Component
79struct PluginUserExample {
80  @StorageLink("plugincount") plugincount: Object[] = [
81    { source: 'plugincomponent1', bundleName: 'com.example.plugin' } as source2BundleName,
82    { source: 'plugintemplate', bundleName: 'com.example.myapplication' } as source2BundleName,
83    { source: 'plugintemplate', bundleName: 'com.example.myapplication' } as source2BundleName]
84
85  build() {
86    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
87      Text('Hello World')
88        .fontSize(50)
89        .fontWeight(FontWeight.Bold)
90      Button('Register Request Listener')
91        .fontSize(30)
92        .width(400)
93        .height(100)
94        .margin({top:20})
95        .onClick(()=>{
96          plugin.onListener()
97          console.log("Button('Register Request Listener')")
98        })
99      Button('Request')
100        .fontSize(50)
101        .width(400)
102        .height(100)
103        .margin({ top: 20 })
104        .onClick(() => {
105          plugin.Request()
106          console.log("Button('Request')")
107        })
108      ForEach(this.plugincount, (item: source2BundleName) => {
109        PluginComponent({
110          template: { source: 'PluginProviderExample', bundleName: 'com.example.plugin' },
111          data: { 'countDownStartValue': 'new countDownStartValue' }
112        }).size({ width: 500, height: 100 })
113          .onComplete(() => {
114            console.log("onComplete")
115          })
116          .onError((info:Info) => {
117            console.log("onComplete" + info.errcode + ":" + info.msg)
118          })
119      })
120    }
121    .width('100%')
122    .height('100%')
123  }
124}
125```
126
127### PluginComponent Provider
128
129```ts
130//PluginProviderExample.ets
131import plugin from "./plugin_component"
132
133@Entry
134@Component
135struct PluginProviderExample {
136  @State message: string = 'no click!'
137
138  build() {
139    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
140      Button('Register Push Listener')
141        .fontSize(30)
142        .width(400)
143        .height(100)
144        .margin({top:20})
145        .onClick(()=>{
146          plugin.onListener()
147          console.log("Button('Register Push Listener')")
148        })
149      Button('Push')
150        .fontSize(30)
151        .width(400)
152        .height(100)
153        .margin({top:20})
154        .onClick(()=>{
155          plugin.Push()
156          this.message = "Button('Push')"
157          console.log("Button('Push')")
158        })
159      Text(this.message)
160        .height(150)
161        .fontSize(30)
162        .padding(5)
163        .margin(5)
164    }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
165  }
166}
167```
168
169### PluginComponent Tools
170
171#### FA Model
172```js
173// The sample code applies only to JS source files.
174//plugin_component.js
175import pluginComponentManager from '@ohos.pluginComponent'
176
177function onPushListener(source, template, data, extraData) {
178  console.log("onPushListener template.source=" + template.source)
179  var jsonObject = JSON.parse(data.componentTemplate.source)
180  console.log("request_callback1:source json object" + jsonObject)
181  var jsonArry = jsonObject.ExternalComponent
182  for (var i in jsonArry) {
183    console.log(jsonArry[i])
184  }
185  console.log("onPushListener:source json object" + jsonObject)
186  console.log("onPushListener:source json string" + JSON.stringify(jsonObject))
187  console.log("onPushListener template.ability=" + template.ability)
188  console.log("onPushListener data=" + JSON.stringify(data))
189  console.log("onPushListener extraData=" + JSON.stringify(extraData))
190}
191
192function onRequestListener(source, name, data)
193{
194    console.log("onRequestListener name=" + name);
195    console.log("onRequestListener data=" + JSON.stringify(data));
196    return {template:"plugintemplate", data:data};
197}
198
199export default {
200  //register listener
201  onListener() {
202    pluginComponentManager.on("push", onPushListener)
203    pluginComponentManager.on("request", onRequestListener)
204  },
205  Push() {
206    // The component provider proactively sends data.
207    pluginComponentManager.push(
208      {
209        want: {
210          bundleName: "com.example.plugin",
211          abilityName: "com.example.myapplication.PluginProviderExample",
212        },
213        name: "PluginProviderExample",
214        data: {
215          "key_1": "plugin component test",
216          "key_2": 34234
217        },
218        extraData: {
219          "extra_str": "this is push event"
220        },
221        jsonPath: "",
222      },
223      (err, data) => {
224        console.log("push_callback: push ok!");
225      }
226    )
227  },
228  Request() {
229    // The component user proactively sends data.
230    pluginComponentManager.request({
231        want: {
232          bundleName: "com.example.plugin",
233          abilityName: "com.example.myapplication.PluginProviderExample",
234        },
235        name: "PluginProviderExample",
236        data: {
237          "key_1": "plugin component test",
238          "key_2": 34234
239        },
240        jsonPath: "",
241      },
242      (err, data) => {
243        console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability)
244        console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source)
245        var jsonObject = JSON.parse(data.componentTemplate.source)
246        console.log("request_callback:source json object" + jsonObject)
247        var jsonArry = jsonObject.ExternalComponent
248        for (var i in jsonArry) {
249          console.log(jsonArry[i])
250        }
251        console.log("request_callback:source json string" + JSON.stringify(jsonObject))
252        console.log("request_callback: data=" + JSON.stringify(data.data))
253        console.log("request_callback: extraData=" + JSON.stringify(data.extraData))
254      }
255    )
256  }
257}
258```
259
260#### Stage Model
261```js
262// The sample code applies only to JS source files.
263//plugin_component.js
264import pluginComponentManager from '@ohos.pluginComponent'
265
266function onPushListener(source, template, data, extraData) {
267  console.log("onPushListener template.source=" + template.source)
268  var jsonObject = JSON.parse(data.componentTemplate.source)
269  console.log("request_callback1:source json object" + jsonObject)
270  var jsonArry = jsonObject.ExternalComponent
271  for (var i in jsonArry) {
272    console.log(jsonArry[i])
273  }
274  console.log("onPushListener:source json object" + jsonObject)
275  console.log("onPushListener:source json string" + JSON.stringify(jsonObject))
276  console.log("onPushListener template.ability=" + template.ability)
277  console.log("onPushListener data=" + JSON.stringify(data))
278  console.log("onPushListener extraData=" + JSON.stringify(extraData))
279}
280
281function onRequestListener(source, name, data)
282{
283    console.log("onRequestListener name=" + name);
284    console.log("onRequestListener data=" + JSON.stringify(data));
285    return {template:"plugintemplate", data:data};
286}
287
288export default {
289  //register listener
290  onListener() {
291    pluginComponentManager.on("push", onPushListener)
292    pluginComponentManager.on("request", onRequestListener)
293  },
294  Push() {
295    // The component provider proactively sends data.
296    pluginComponentManager.push(
297      {
298        owner: {
299          bundleName: "com.example.myapplication",
300          abilityName: "com.example.myapplication.MainAbility",
301        },
302        target: {
303          bundleName: "com.example.plugin",
304          abilityName: "com.example.myapplication.PluginProviderExample",
305        },
306        name: "PluginProviderExample",
307        data: {
308          "key_1": "plugin component test",
309          "key_2": 34234
310        },
311        extraData: {
312          "extra_str": "this is push event"
313        },
314        jsonPath: "",
315      },
316      (err, data) => {
317        console.log("push_callback: push ok!");
318      }
319    )
320  },
321  Request() {
322    // The component user proactively sends data.
323    pluginComponentManager.request({
324        owner: {
325          bundleName: "com.example.myapplication",
326          abilityName: "com.example.myapplication.MainAbility",
327        },
328        target: {
329          bundleName: "com.example.plugin",
330          abilityName: "com.example.myapplication.PluginProviderExample",
331        },
332        name: "PluginProviderExample",
333        data: {
334          "key_1": "plugin component test",
335          "key_2": 34234
336        },
337        jsonPath: "",
338      },
339      (err, data) => {
340        console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability)
341        console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source)
342        var jsonObject = JSON.parse(data.componentTemplate.source)
343        console.log("request_callback:source json object" + jsonObject)
344        var jsonArry = jsonObject.ExternalComponent
345        for (var i in jsonArry) {
346          console.log(jsonArry[i])
347        }
348        console.log("request_callback:source json string" + JSON.stringify(jsonObject))
349        console.log("request_callback: data=" + JSON.stringify(data.data))
350        console.log("request_callback: extraData=" + JSON.stringify(data.extraData))
351      }
352    )
353  }
354}
355```
356