• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Processing Web Page Content by Interacting with the System Clipboard
2
3ArkWeb provides the capability of interacting with the system clipboard to cut, copy, and paste various types of data through the following methods: the [Menu](web_menu.md) component, keyboard shortcuts, and [W3C clipboard API and events](https://www.w3.org/TR/clipboard-apis/).
4
5## Using the Menu Component or Keyboard Shortcuts
6
7You can customize options in the menu. When a user selects a specific option, the [cut](../reference/apis-arkweb/arkts-basic-components-web-WebContextMenuResult.md#cut9), [copy](../reference/apis-arkweb/arkts-basic-components-web-WebContextMenuResult.md#copy9) and [copyImage](../reference/apis-arkweb/arkts-basic-components-web-WebContextMenuResult.md#copyimage9) APIs can be called to cut or copy the text, HTML or image data to the system clipboard. The [paste](../reference/apis-arkweb/arkts-basic-components-web-WebContextMenuResult.md#paste9) and [pasteAndMatchStyle](../reference/apis-arkweb/arkts-basic-components-web-WebContextMenuResult.md#pasteandmatchstyle20) APIs can be used to paste the data to the input area of the web page.
8
9For details about how to use the APIs provided by the **Menu** component, see [Processing Web Page Content Using the Menu Component](web_menu.md).
10
11When a device has a physical keyboard, a user can also use keyboard shortcuts **Ctrl+X** (cut), **Ctrl+C** (copy), and **Ctrl+V** (paste) to interact with the clipboard.
12
13> **NOTE**
14>
15> To access the clipboard content through the [paste](../reference/apis-arkweb/arkts-basic-components-web-WebContextMenuResult.md#paste9) and [pasteAndMatchStyle](../reference/apis-arkweb/arkts-basic-components-web-WebContextMenuResult.md#pasteandmatchstyle20) APIs, you need to [request permissions to access the pasteboard](../basic-services/pasteboard/get-pastedata-permission-guidelines.md) by requesting the **ohos.permission.READ_PASTEBOARD** permission.
16
17## Using the W3C Asynchronous Clipboard API
18
19[Asynchronous clipboard API](https://www.w3.org/TR/clipboard-apis/#async-clipboard-api) provides the methods of reading and writing the system clipboard for you to implement the cutting, copying, and pasting functionalities in web applications.
20
21- Use **writeText** to write text content to the system clipboard.
22
23```javascript
24// Write text content to the clipboard.
25await navigator.clipboard.writeText ("Text content");
26```
27
28- Use **write** to write content of any type to the system clipboard.
29
30```javascript
31// Write HTML content to the clipboard.
32const clipboardItem = new ClipboardItem({
33    'text/html': new Blob (["HTML content"], { type: 'text/html' })
34});
35await navigator.clipboard.write([clipboardItem]);
36```
37
38- Use **readText** to read text from the system clipboard.
39
40```javascript
41// Read text from the clipboard.
42const text = await navigator.clipboard.readText()
43```
44
45- Use **read()** to read any type of content from the system clipboard.
46
47```javascript
48// Read HTML from the clipboard.
49const clipboardItems = await navigator.clipboard.read();
50const htmlBlob = await clipboardItems[0].getType('text/html');
51```
52
53> **NOTE**
54>
55> To access the clipboard content through the **read()** and **readText()** methods of the asynchronous API, you need to [request the permission to access the pasteboard](../basic-services/pasteboard/get-pastedata-permission-guidelines.md): **ohos.permission.READ_PASTEBOARD**.
56
57```ts
58// xxx.ets
59import { webview } from '@kit.ArkWeb';
60
61@Entry
62@Component
63struct WebComponent {
64  controller: webview.WebviewController = new webview.WebviewController();
65
66  build() {
67    Column() {
68      Web({ src: $rawfile("clipboard.html"), controller: this.controller })
69    }
70  }
71}
72```
73
74Loaded HTML:
75
76```html
77<!--clipboard.html-->
78<!DOCTYPE html>
79<html lang="zh">
80<head>
81    <meta charset="UTF-8">
82    <meta name="viewport" content="width=device-width, initial-scale=1.0">
83    <title>Clipboard API demo</title>
84    <style>
85        #output {
86            margin-top: 20px;
87            border: 1px solid #ccc;
88            padding: 10px;
89            min-height: 50px;
90        }
91        .button-group {
92            margin-bottom: 10px;
93        }
94    </style>
95</head>
96<body>
97<h1>Clipboard API demo</h1>
98<div class="button-group">
99    <button id="copyTextButton">Copy text</button>;
100    <button id="copyHtmlButton">Copy HTML</button>;
101</div>
102
103<div class="button-group">
104    <button id="pasteTextButton">Paste text</button>;
105    <button id="pasteHtmlButton">Paste HTML</button>;
106    <button id="clearOutputButton">Clear the text box</button>;
107</div>
108
109<div id="result"></div>
110<div id="output" contenteditable="true"></div>
111
112<script>
113    const textContent = "This is some text content";
114    const htmlContent = `<strong><em>This is some HTML content</em></strong>`;
115
116    // Call writeText()
117    async function copyText() {
118        await navigator.clipboard.writeText(textContent);
119        document.getElementById('result').innerText = "The text has been copied to the clipboard.";
120    }
121
122    // Call write()
123    async function copyHtml() {
124        const clipboardItem = new ClipboardItem({
125            'text/html': new Blob([htmlContent], { type: 'text/html' })
126        });
127        await navigator.clipboard.write([clipboardItem]);
128        document.getElementById('result').innerText = "HTML has been copied to the clipboard.";
129    }
130
131    // Call readText()
132    async function pasteText() {
133        const text = await navigator.clipboard.readText();
134        document.getElementById('output').innerText = text;
135    }
136
137    // Call read()
138    async function pasteHtml() {
139        const items = await navigator.clipboard.read();
140        for (const item of items) {
141            const types = item.types;
142            if (types.includes('text/html')) {
143                const blob = await item.getType('text/html');
144                const html = await blob.text();
145                document.getElementById('output').innerHTML = html;
146                return;
147            }
148        }
149        document.getElementById ('result').innerText = "No HTML content on the clipboard.";
150    }
151
152    function clearOutput() {
153        document.getElementById('result').innerText = " ";
154        document.getElementById('output').innerHTML = '';
155    }
156
157    // Listen for events.
158    document.getElementById('copyTextButton').addEventListener('click', copyText);
159    document.getElementById('copyHtmlButton').addEventListener('click', copyHtml);
160    document.getElementById('pasteTextButton').addEventListener('click', pasteText);
161    document.getElementById('pasteHtmlButton').addEventListener('click', pasteHtml);
162    document.getElementById('clearOutputButton').addEventListener('click', clearOutput);
163</script>
164</body>
165</html>
166```
167
168Configure permissions for the **module.json5** file.
169
170```json
171// module.json5
172{
173  "module" : {
174    // ...
175    "requestPermissions":[
176      {
177        "name" : "ohos.permission.READ_PASTEBOARD",
178        "reason": "$string:module_desc",
179        "usedScene": {
180          "abilities": [
181            "FormAbility"
182          ],
183          "when":"inuse"
184        }
185      }
186    ]
187  }
188}
189```
190
191![clipboard_api](./figures/web-clipboard_api.gif)
192
193## Using the W3C Clipboard Event API
194
195[Clipboard events](https://www.w3.org/TR/clipboard-apis/#clipboard-events-and-interfaces) describes the **cut**, **copy**, and **paste** events related to the clipboard. When a user performs the cut, copy, or paste operation, the corresponding event is triggered. By listening for these events, you can read and write the system clipboard or intercept the default behavior to change the copy or paste result.
196
197```ts
198// xxx.ets
199import { webview } from '@kit.ArkWeb';
200
201@Entry
202@Component
203struct WebComponent {
204  controller: webview.WebviewController = new webview.WebviewController();
205
206  build() {
207    Column() {
208      Web({ src: $rawfile("clipboard_event.html"), controller: this.controller })
209    }
210  }
211}
212```
213
214Loaded HTML:
215
216```html
217<!--clipboard_event.html-->
218<!DOCTYPE html>
219<html lang="zh">
220<head>
221    <meta charset="UTF-8">
222    <meta name="viewport" content="width=device-width, initial-scale=1.0">
223    <title>Clipboard Event demo</title>
224    <style>
225        .output {
226            margin-top: 20px;
227            border: 1px solid #ccc;
228            padding: 10px;
229            max-width: 400px;
230        }
231    </style>
232</head>
233<body>
234<h2>Example of listening a clipboad event</h2>
235<textarea id="inputArea" rows="4" cols="50" placeholder="Input text here and try to copy and paste..."></textarea>;
236
237<div class="output" id="output">
238    <h3>Output content:</h3>
239    <p id="resultText">No content is copied or pasted. </p>
240</div>
241
242<script>
243    const inputArea = document.getElementById('inputArea');
244    const resultText = document.getElementById('resultText');
245
246    // Listen to the copy event.
247    inputArea.addEventListener('copy', (event) => {
248        const selection = document.getSelection();
249        const copiedText = selection.toString() + "(Copied from ArkWeb)
250        event.clipboardData.setData("text/plain", copiedText);
251        event.preventDefault();
252        resultText.textContent = `Copied content: "${copiedText}"`;
253    });
254
255    // Listen for the paste event.
256    inputArea.addEventListener('paste', (event) => {
257        const pastedData = event.clipboardData.getData('text');
258        resultText.textContent = `Pasted content: "${pastedData}"`;
259    });
260
261    // Listen for the cut event.
262    inputArea.addEventListener('cut', (event) => {
263        const selection = document.getSelection();
264        const cutText = selection.toString() + "(Cut from ArkWeb)
265        event.clipboardData.setData("text/plain", cutText);
266        selection.deleteFromDocument();
267        event.preventDefault();
268        resultText.textContent = `Copied content: "${cutText}"`;
269    });
270</script>
271</body>
272</html>
273```
274
275![clipboard_event](./figures/web-clipboard_event.gif)
276
277## Setting Copy Options
278
279You can set the [copyOptions](../reference/apis-arkweb/arkts-basic-components-web-attributes.md#copyoptions11) attribute of a **Web** component to specify the copy scope of the clipboard on the **Web** component. The available options are **CopyOptions.None** (copy is not supported), **CopyOptions.InApp** (in-application copy is supported), and **CopyOptions.LocalDevice** (in-device copy is supported). The default value is **CopyOptions.LocalDevice**, indicating that copy within a device is supported by default.
280
281```ts
282// xxx.ets
283import { webview } from '@kit.ArkWeb';
284
285@Entry
286@Component
287struct WebComponent {
288  controller: webview.WebviewController = new webview.WebviewController();
289  @State copyOption: CopyOptions = CopyOptions.LocalDevice;
290
291  build() {
292    Column() {
293      Web({ src: $rawfile("copyOptions.html"), controller: this.controller })
294        .copyOptions(this.copyOption)
295    }
296  }
297}
298```
299
300Loaded HTML:
301
302```html
303<!--copyOptions.html-->
304<!DOCTYPE html>
305<html lang="zh">
306<head>
307    <meta charset="UTF-8">
308    <meta name="viewport" content="width=device-width, initial-scale=1.0">
309    <title>Clipboard CopyOption demo</title>
310</head>
311<body>
312<h2>Example of clipboard CopyOption</h2>
313<textarea id="inputArea"></textarea>
314</body>
315</html>
316```
317