Rayrun

What is the method to access clipboard content using Playwright?

Answer

Accessing Clipboard Content with Playwright

You can easily read from the clipboard using Playwright's navigator.clipboard.readText() method. This method returns a promise that resolves with the text content of the clipboard. It's important to note that this method is only available in secure contexts, like HTTPS pages or localhost.

Here's a quick example:

import { test } from '@playwright/test';

test('read from clipboard', async ({ page }) => {
  const text = await page.evaluate(() => navigator.clipboard.readText());
  console.log(text);
});

In this code, page.evaluate() is used to execute JavaScript code in the context of the page. It calls navigator.clipboard.readText() and logs the result.

If the clipboard doesn't contain any text, navigator.clipboard.readText() will return an empty string.

For non-text data (like images or files), you can use other navigator.clipboard methods like read(). These methods also return promises that resolve with their respective data types.

So, reading from the clipboard with Playwright is pretty straightforward and can be done with just a few lines of code. Happy testing!

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.