1# Requesting Permissions to Access the Pasteboard
2
3## Overview
4
5In API version 12 and later, permission control is added to the pasteboard reading API to enhance user privacy protection.
6
7Related APIs:
8
9| Name| Description                                                                                                                                       |
10| -------- |----------------------------------------------------------------------------------------------------------------------------------------|
11| getData( callback: AsyncCallback<PasteData>): void | Reads a **PasteData** object from the pasteboard. This API uses an asynchronous callback to return the result.|
12| getData(): Promise<PasteData> | Reads a **PasteData** object from the pasteboard. This API uses a promise to return the result.|
13| getDataSync(): PasteData | Reads data from the system pasteboard. This API returns the result synchronously.|
14
15## Accessing Pasteboard Content
16
17Applications can access the pasteboard content in either of the following ways:
18
19- Using security components
20
21    Applications that use the [security components](../../../application-dev/security/AccessToken/pastebutton.md) to access the pasteboard content do not need to request the permission.
22
23    Applications that use the security components can access the pasteboard content without any adaptation.
24
25- Requesting the **ohos.permission.READ_PASTEBOARD** permission
26
27    **READ_PASTEBOARD** is a user_grant permission. Applications that use customized components can request the **ohos.permission.READ_PASTEBOARD** permission to access the pasteboard content with user authorization.
28
29    To request the **ohos.permission.READ_PASTEBOARD** permission, perform the following steps:
30
31    1. Configure the required permission in **module.json5**. For details, see [Requesting Application Permissions](../../../application-dev/security/AccessToken/determine-application-mode.md).
32    ```ts
33    "requestPermissions": [
34      {
35      "name": "ohos.permission.READ_PASTEBOARD",
36      }
37    ]
38    ```
39
40    2. Add a user authorization dialog box before the call to **getData**.
41    ```ts
42    import { hilog } from '@kit.PerformanceAnalysisKit';
43    import { abilityAccessCtrl, common, Permissions, UIAbility, bundleManager } from '@kit.AbilityKit';
44    import { window } from '@kit.ArkUI';
45    import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
46
47    async function checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
48      let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
49      let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;
50
51      // Obtain the token ID of the application.
52      let tokenId: number = 0;
53      try {
54        let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
55        let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
56        tokenId = appInfo.accessTokenId;
57      } catch (error) {
58        let err: BusinessError = error as BusinessError;
59        console.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`);
60      }
61
62      // Check whether the user has granted the permission.
63      try {
64        grantStatus = await atManager.checkAccessToken(tokenId, permission);
65      } catch (error) {
66        let err: BusinessError = error as BusinessError;
67        console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`);
68      }
69
70      return grantStatus;
71    }
72
73    @Entry
74    @Component
75    struct Index {
76      @State message: string = 'Hello World';
77      @State msgList: Array<string> = [];
78      // @State oaid: string = '';
79      @State permission_state: boolean = true;
80
81      reqPermissionsFromUser(permissions: Array<Permissions>): void {
82        let context = getContext(this) as common.UIAbilityContext;
83        let atManager = abilityAccessCtrl.createAtManager();
84        // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
85        atManager.requestPermissionsFromUser(context, permissions).then((data) => {
86          let grantStatus: Array<number> = data.authResults;
87          let length: number = grantStatus.length;
88          for (let i = 0; i < length; i++) {
89            if (grantStatus[i] === 0) {
90              // If the user grants the permission, the application can continue to access the target operation.
91              this.permission_state = true;
92              this.msgList.push ('Permission requested successfully.');
93            }
94            else {
95              // If the user denies the permission, display a message indicating that user authorization is required, and direct the user to set the permission in the Settings page.
96              // openPermissionsInSystemSettings();
97              console.error("user did not grant!")
98              this.permission_state = false;
99              this.msgList.push ('Failed to request the permission.');
100            }
101          }
102          // Authorization successful.
103        }).catch((err: String) => {
104        })
105      }
106
107      async getPaste() {
108        const permissions: Array<Permissions> = ['ohos.permission.READ_PASTEBOARD'];
109        let grantStatus1: abilityAccessCtrl.GrantStatus = await checkAccessToken(permissions[0]);
110
111        if (grantStatus1 === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
112          try {
113            let systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
114            systemPasteboard.getData((err: BusinessError, pasteData: pasteboard.PasteData) => {
115              if (err) {
116                console.error('Failed to get PasteData. Cause: ' + err.message);
117                return;
118              }
119              let text: string = pasteData.getPrimaryText();
120              this.msgList.push ('Pasteboard content: '+text);
121            });
122          } catch (err) {
123            hilog.error(0x0000, 'testTag', '%{public}s', `get oaid by promise catch error: ${err.code} ${err.message}`);
124          }
125        } else {
126          // Request the permission.
127          if(this.permission_state) {
128            this.reqPermissionsFromUser(permissions)
129          }else{
130
131          }
132        }
133      }
134    }
135    ```
136