• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Using the Pasteboard to Copy and Paste
2<!--Kit: Basic Services Kit-->
3<!--Subsystem: MiscServices-->
4<!--Owner: @yangxiaodong41-->
5<!--Designer: @guo867-->
6<!--Tester: @maxiaorong2-->
7<!--Adviser: @HelloCrease-->
8
9## When to Use
10
11The [pasteboard](../../reference/apis-basic-services-kit/js-apis-pasteboard.md) allows you to copy and paste data. For example, you can copy text content and paste it to Notepad, or copy a photo from Gallery and paste it to Files.
12
13## Constraints
14
15- The pasteboard content, including system service metadata and application settings, has a maximum size of 128 MB by default. For PCs/2-in-1 devices, the maximum size can be changed through system settings, with a valid range from 128 MB to 2 GB.
16- To ensure the accuracy of the pasteboard data, only one copy can be performed at a time.
17- In API version 12 and later, [permission control](get-pastedata-permission-guidelines.md) is added to the pasteboard reading API to enhance user privacy protection.
18
19## Using a Basic Data Types
20
21Currently, the following basic data types are supported for copy and paste: text, HTML, URI, Want, and pixel map. The data types supported by ArkTS APIs are different from those supported by NDK APIs. You need to match the data types with the corresponding APIs during usage.
22
23You are advised to use the solution discussed here to implement the copy-and-paste function for new applications.
24
25### Mapping between ArkTS and NDK Data Types
26| ArkTS| NDK                                                                                                                                       |
27| -------- |----------------------------------------------------------------------------------------------------------------------------------------|
28| MIMETYPE_PIXELMAP : "pixelMap" | UDMF_META_OPENHARMONY_PIXEL_MAP : "openharmony.pixel-map" |
29| MIMETYPE_TEXT_HTML : "text/html" | UDMF_META_HTML : "general.html" |
30| MIMETYPE_TEXT_PLAIN : "text/plain" | UDMF_META_PLAIN_TEXT : "general.plain-text" |
31| MIMETYPE_TEXT_URI : "text/uri" | UDMF_META_GENERAL_FILE_URI : "general.file-uri" |
32| MIMETYPE_TEXT_WANT : "text/want" | Not supported.|
33
34The ArkTS data type corresponds to the pasteboard type. For details, see [ohos.pasteboard](../../reference/apis-basic-services-kit/js-apis-pasteboard.md). The NDK data type corresponds to the unified data management framework. For details, see [UDMF](../../reference/apis-arkdata/capi-udmf.md).
35
36### Available APIs
37
38For details about the APIs, see [API Reference](../../reference/apis-basic-services-kit/js-apis-pasteboard.md#getdata9).
39
40After obtaining URI data using the **getData** API, use the [fs.copy](../../reference/apis-core-file-kit/js-apis-file-fs.md#fscopy11) API of File Manager to obtain the file.
41
42| Name| Description                                                                                                                                       |
43| -------- |----------------------------------------------------------------------------------------------------------------------------------------|
44| setData(data: PasteData, callback: AsyncCallback&lt;void&gt;): void | Writes a **PasteData** object to the pasteboard. This API uses an asynchronous callback to return the result.|
45| setData(data: PasteData): Promise&lt;void&gt; | Writes a **PasteData** object to the pasteboard. This API uses a promise to return the result.|
46| getData( callback: AsyncCallback&lt;PasteData&gt;): void | Reads a **PasteData** object from the pasteboard. This API uses an asynchronous callback to return the result.|
47| getData(): Promise&lt;PasteData&gt; | Reads a **PasteData** object from the pasteboard. This API uses a promise to return the result.|
48| getDataSync(): PasteData | Reads a **PasteData** object from the pasteboard. This API returns the result synchronously and cannot be called in the same thread as **SetData**.|
49
50### Example
51```ts
52import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
53import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
54
55export default class EntryAbility extends UIAbility {
56  async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
57    // Obtain the system pasteboard object.
58    let text = "test";
59    // Create a pasteboard content object of the plain text type.
60    let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
61    // Write data to the system pasteboard.
62    let systemPasteboard = pasteboard.getSystemPasteboard();
63    await systemPasteboard.setData(pasteData);
64    // Read data from the system pasteboard.
65    systemPasteboard.getData().then((data) => {
66      let outputData = data;
67      // Obtain the number of records from the pasteboard.
68      let recordCount = outputData.getRecordCount();
69      // Obtain the corresponding record information from the pasteboard data.
70      for (let i = 0; i < recordCount; i++) {
71        let record = outputData.getRecord(i).toPlainText();
72        console.info('Get data success, record:' + record);
73      }
74    }).catch((error: BusinessError) => {
75      // Error case
76    })
77  }
78}
79```
80
81## Using a Unified Data Object
82
83To facilitate data interactions between the pasteboard and other applications and reduce the workload of data type adaptation, the pasteboard supports a unified data object for copying and pasting. For details about the unified data object, see [Unified Data Channel](../../reference/apis-arkdata/js-apis-data-unifiedDataChannel.md).
84
85Currently, the following basic data types are supported for copy and paste: text and HTML. The data types supported by ArkTS APIs are different from those supported by NDK APIs. You need to match the data types with the corresponding APIs during usage.
86
87### Available APIs
88
89For details about the APIs, see [API Reference](../../reference/apis-basic-services-kit/js-apis-pasteboard.md#getunifieddata12).
90
91| Name| Description                                                                                                                                       |
92| -------- |----------------------------------------------------------------------------------------------------------------------------------------|
93| setUnifiedData(data: udc.UnifiedData): Promise\<void\> | Writes the data of a unified data object to the system pasteboard. |
94| setUnifiedDataSync(data: udc.UnifiedData): void | Writes the data of a unified data object to the system pasteboard. This API returns the result synchronously.                                                                                                                         |
95| getUnifiedData(): Promise\<udc.UnifiedData\> | Reads the data of a unified data object from the system pasteboard.                                                                                                                         |
96| getUnifiedDataSync(): udc.UnifiedData | Reads the data of a unified data object from the system pasteboard. This API returns the result synchronously. |
97
98### Example
99```ts
100import {BusinessError, pasteboard} from '@kit.BasicServicesKit';
101import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
102
103// Construct a PlainText data object.
104let plainText : uniformDataStruct.PlainText = {
105    uniformDataType: uniformTypeDescriptor.UniformDataType.PLAIN_TEXT,
106    textContent : 'PLAINTEXT_CONTENT',
107    abstract : 'PLAINTEXT_ABSTRACT',
108}
109let record = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT, plainText);
110let data = new unifiedDataChannel.UnifiedData();
111data.addRecord(record);
112
113// Save a piece of PlainText data to the system pasteboard.
114let systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
115systemPasteboard.setUnifiedData(data).then((data: void) => {
116    console.info('Succeeded in setting UnifiedData.');
117    // The data is successfully saved, which is a normal case.
118}).catch((err: BusinessError) => {
119    console.error('Failed to set UnifiedData. Cause: ' + err.message);
120    // Error case
121});
122
123// Read the text data from the system pasteboard.
124systemPasteboard.getUnifiedData().then((data) => {
125    let records: Array<unifiedDataChannel.UnifiedRecord> = data.getRecords();
126    for (let j = 0; j < records.length; j++) {
127        if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
128            let text = records[j].getValue() as uniformDataStruct.PlainText;
129            console.info(`${j + 1}.${text.textContent}`);
130        }
131    }
132}).catch((err: BusinessError) => {
133    console.error('Failed to get UnifiedData. Cause: ' + err.message);
134    // Error case
135});
136```
137
138<!--RP1-->
139<!--RP1End-->
140