|
| 1 | +import type { Page } from '@playwright/test'; |
| 2 | +import { SHORTKEY } from '../utils/index.js'; |
| 3 | + |
| 4 | +class Clipboard { |
| 5 | + constructor(private page: Page) {} |
| 6 | + |
| 7 | + async copy() { |
| 8 | + await this.page.keyboard.press(`${SHORTKEY}+c`); |
| 9 | + } |
| 10 | + |
| 11 | + async cut() { |
| 12 | + await this.page.keyboard.press(`${SHORTKEY}+x`); |
| 13 | + } |
| 14 | + |
| 15 | + async paste() { |
| 16 | + await this.page.keyboard.press(`${SHORTKEY}+v`); |
| 17 | + } |
| 18 | + |
| 19 | + async writeText(value: string) { |
| 20 | + await this.write(value, 'text/plain'); |
| 21 | + } |
| 22 | + |
| 23 | + async writeHTML(value: string) { |
| 24 | + return this.write(value, 'text/html'); |
| 25 | + } |
| 26 | + |
| 27 | + async readText() { |
| 28 | + return this.read('text/plain'); |
| 29 | + } |
| 30 | + |
| 31 | + async readHTML() { |
| 32 | + const html = await this.read('text/html'); |
| 33 | + return html.replace(/<meta[^>]*>/g, ''); |
| 34 | + } |
| 35 | + |
| 36 | + private async read(type: string) { |
| 37 | + const isHTML = type === 'text/html'; |
| 38 | + await this.page.evaluate((isHTML) => { |
| 39 | + const dataContainer = document.createElement(isHTML ? 'div' : 'textarea'); |
| 40 | + if (isHTML) dataContainer.setAttribute('contenteditable', 'true'); |
| 41 | + dataContainer.id = '_readClipboard'; |
| 42 | + document.body.appendChild(dataContainer); |
| 43 | + dataContainer.focus(); |
| 44 | + return dataContainer; |
| 45 | + }, isHTML); |
| 46 | + await this.paste(); |
| 47 | + const locator = this.page.locator('#_readClipboard'); |
| 48 | + const data = await (isHTML ? locator.innerHTML() : locator.inputValue()); |
| 49 | + await locator.evaluate((node) => node.remove()); |
| 50 | + return data; |
| 51 | + } |
| 52 | + |
| 53 | + private async write(data: string, type: string) { |
| 54 | + await this.page.evaluate( |
| 55 | + async ({ data, type }) => { |
| 56 | + if (type === 'text/html') { |
| 57 | + await navigator.clipboard.write([ |
| 58 | + new ClipboardItem({ |
| 59 | + 'text/html': new Blob([data], { type: 'text/html' }), |
| 60 | + }), |
| 61 | + ]); |
| 62 | + } else { |
| 63 | + await navigator.clipboard.writeText(data); |
| 64 | + } |
| 65 | + }, |
| 66 | + { data, type }, |
| 67 | + ); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +export default Clipboard; |
0 commit comments