playwright-fluent
Version:
Fluent API around playwright
51 lines (50 loc) • 2.14 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeText = exports.defaultTypeTextOptions = void 0;
const utils_1 = require("../../../utils");
exports.defaultTypeTextOptions = {
delay: 50,
clearExistingTextBeforeTyping: true,
};
async function typeText(text, page, options) {
if (!page) {
throw new Error(`Cannot type 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 typing text.`);
}
const handle = focusedElement.asElement();
if (handle === null) {
throw new Error(`You must first click on an editable element before typing 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 typing text.`);
}
if (currentTagName === 'P' && !isContentEditable) {
throw new Error(`You must first click on an editable element before typing text.`);
}
if (options.clearExistingTextBeforeTyping) {
const tripleClickOptions = {
...utils_1.defaultWaitUntilOptions,
button: 'left',
delay: options.delay,
clickCount: 3,
};
await handle.click(tripleClickOptions);
const selectionRange = await handle.evaluate((el) => {
if (el && typeof el.selectionStart === 'number' && typeof el.selectionEnd === 'number') {
return el.selectionEnd - el.selectionStart;
}
return 0;
});
if (selectionRange > 0) {
await (0, utils_1.sleep)(options.delay * 5);
await (0, utils_1.toPage)(page).keyboard.press('Backspace', { delay: options.delay });
}
}
await (0, utils_1.toPage)(page).keyboard.type(text, options);
}
exports.typeText = typeText;
;