首页 > 解决方案 > 如何使用 Puppeteer 粘贴文本?

问题描述

我正在尝试为我的 React 应用程序中的输入编写一个测试(使用 jest-puppeteer),它以独特的方式处理自动完成或复制/粘贴的字符串。

我希望通过使用 Puppeteer,我可以将文本粘贴到输入中,然后验证页面是否正确更新。不幸的是,我找不到任何可行的例子来说明如何做到这一点。

我尝试使用page.keyboard模拟CMD+C&CMD+V但似乎这些命令在 Puppeteer 中不起作用。

我还尝试使用诸如剪贴板之类的库来写入和读取操作系统剪贴板。虽然剪贴板确实适用于写入(复制),但读取(粘贴)似乎不会影响 Puppeteer 运行的页面。

我已经使用多种方法成功复制了文本,但无法粘贴到输入中。我已经通过为文档添加事件侦听"copy"器来验证这个假设。"paste"事件"copy"触发,但没有任何方法导致"paste"事件触发。

以下是我尝试过的几种方法:

await clipboardy.write('1234'); // writes "1234" to clipboard
await page.focus("input");
await clipboardy.read(); // Supposedly pastes from clipboard
// assert input has updated
await clipboardy.write('1234');
await page.focus("input");
await page.keyboard.down('Meta');
await page.keyboard.press('KeyV');
await page.keyboard.up('Meta');
// assert input has updated
await page.evaluate(() => {
  const input = document.createElement('input');
  document.body.appendChild(input);
  input.value = '1234';
  input.focus();
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
});
wait page.focus("input");
await page.keyboard.down('Meta');
await page.keyboard.press('KeyV');
await page.keyboard.up('Meta');

我认为这里唯一缺少的部分是粘贴文本;但是如何使用 Puppeteer 粘贴文本?

标签: puppeteer

解决方案


这适用于我的剪贴板,但不适用于无头启动它:

await clipboardy.write('foo')

const input= await puppeteerPage.$(inputSelector)
await input.focus()

await puppeteerPage.keyboard.down('Control')
await puppeteerPage.keyboard.press('V')
await puppeteerPage.keyboard.up('Control')

如果你让它在无头模式下工作,请告诉我。

我也尝试了剪贴板 API,但无法编译:

const browser = await getBrowser()
const context = browser.defaultBrowserContext();
// set clipBoard API permissions
context.clearPermissionOverrides()
context.overridePermissions(config.APPLICATION_URL, ['clipboard-write'])
puppeteerPage = await browser.newPage()

await puppeteerPage.evaluate((textToCopy) =>{
  navigator.clipboard.writeText(textToCopy)
}, 'bar')

const input= await puppeteerPage.$(inputSelector)
await input.focus()

await puppeteerPage.evaluate(() =>{
  navigator.clipboard.readText()
})

推荐阅读