clipboardpuppeteer

How do I access the contents of the clipboard from within a headless puppeteer test?


I'm writing a test that uses puppeteer to test a component that copies something to the clipboard when it is interacted with. I want to test that the contents of the clipboard are correct after interacting. Other resources like this github issue mention using a tool like clipboardy to accomplish this. I tried using that and it works locally, but when run in my headless CI server, it complains about not having access to the X environment. Is there a way to access the clipboard without starting an X server?

I'm writing a test like this:

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://mypage.com');

await page.click('#my-component');

// This fails in a headless environment
expect(clipboardy.readSync()).toEqual("Some text");

Solution

  • By adding the 'clipboard-read' permission to puppeteer and using the Clipboard API, you can run navigator.clipboard.readText() to read from the clipboard in a test. This will work even in a headless environment:

    const browser = await puppeteer.launch();
    const context = browser.defaultBrowserContext();
    await context.overridePermissions(/* browser origin */, ['clipboard-read']);
    const page = await browser.newPage();
    await page.goto('https://mypage.com');
    
    await page.click('#my-component');
    
    expect(await page.evaluate(() => navigator.clipboard.readText()))
      .toEqual("Some text");
    

    Documentation of context.overridePermissions()