如何使用 Puppeteer 粘贴文本?

san*_*ham 9 puppeteer

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

我希望通过使用 Puppeteer,我可以将文本粘贴到输入中,然后验证页面是否正确更新。不幸的是,我找不到任何有关如何执行此操作的工作示例。

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

我还尝试使用诸如clipboardy 之类的库来写入和读取操作系统剪贴板。虽然剪贴板确实适用于写入(复制),但似乎读取(粘贴)不会影响 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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');
Run Code Online (Sandbox Code Playgroud)

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

Max*_*ont 5

这对我使用clipboardy 有效,但当我在 headless 中启动它时无效:

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')
Run Code Online (Sandbox Code Playgroud)

如果你让它在无头中工作,告诉我。

我也尝试了剪贴板 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()
})
Run Code Online (Sandbox Code Playgroud)