UNPKG

playwright-fluent

Version:
75 lines (74 loc) 3.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.pasteText = exports.defaultPasteTextOptions = void 0; const utils_1 = require("../../../utils"); exports.defaultPasteTextOptions = { delay: 50, handlePasteEvent: false, clearExistingContent: true, }; async function pasteText(text, page, options) { if (!page) { throw new Error(`Cannot paste text '${text}' because no browser has been launched`); } const focusedElement = await page.evaluateHandle(() => window.document.activeElement); if (focusedElement === null) { throw new Error(`You must first click on an editable element before pasting text.`); } const handle = focusedElement.asElement(); if (handle === null) { throw new Error(`You must first click on an editable element before pasting text.`); } const currentTagName = await handle.evaluate((node) => node.tagName); const isContentEditable = await handle.evaluate((node) => node.isContentEditable); if (currentTagName === 'BODY') { throw new Error(`You must first click on an editable element before pasting text.`); } if (currentTagName === 'P' && !isContentEditable) { throw new Error(`You must first click on an editable element before pasting text.`); } if (currentTagName === 'DIV' && !isContentEditable) { throw new Error(`You must first click on an editable element before clearing text.`); } if (options.clearExistingContent) { const tripleClickOptions = { ...utils_1.defaultWaitUntilOptions, button: 'left', delay: options.delay, clickCount: 3, }; await handle.click(tripleClickOptions); await (0, utils_1.sleep)(options.delay * 5); await (0, utils_1.toPage)(page).keyboard.press('Backspace', { delay: options.delay }); } await handle.evaluate((node, { content, handlePasteEvent }) => { function attachPasteEvent(el) { el.addEventListener('paste', (event) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const content = (event.clipboardData || window.clipboardData).getData('text'); const input = event.target; if (event.target && input && input.tagName === 'INPUT') { input.value += content; event.preventDefault(); return; } event.target.innerText += content; event.preventDefault(); }); } if (handlePasteEvent) { attachPasteEvent(node); } // eslint-disable-next-line @typescript-eslint/no-explicit-any window.clipboardData = { getData: () => content }; const event = new CustomEvent('paste', { bubbles: true, }); // eslint-disable-next-line @typescript-eslint/no-explicit-any event.clipboardData = { getData: () => content }; node.dispatchEvent(event); // eslint-disable-next-line @typescript-eslint/no-explicit-any window.clipboardData = undefined; }, { content: text, handlePasteEvent: options.handlePasteEvent }); } exports.pasteText = pasteText;