Skip to main content
SeleniumDecoded
Chapter 3 · Lesson 9 of 9 Actions & Interactions
On this page

Clipboard and Keyboard Shortcuts

Copy, paste and select-all in Selenium with platform-aware modifier keys, read the clipboard via the async Clipboard API, and avoid headless pitfalls.

Selenium 4 Medium 7 min read · Updated · Verified against Selenium 4.52.0
Before you start: Keyboard Actions

“Copy this API key”, “paste a spreadsheet range into the grid”, “Ctrl+S saves the draft”. Shortcut and clipboard features are real product behaviour and deserve tests, but they are where cross-platform differences hurt most. The same test needs Ctrl on Windows and Linux and Command on macOS. Reading the clipboard needs browser permissions and a focused page. Headless and remote browsers have their own clipboards that your test process cannot see.

This lesson shows how to send shortcuts that work on every platform, how to verify copy and paste without touching the operating system clipboard, and how to read the clipboard directly when you need to.

Sending a Shortcut

Selenium gives you two ways to press key combinations: modifier keys inside sendKeys, and the Actions API.

Modifiers in sendKeys

Within a single sendKeys call, modifier keys stay pressed until the end of the call. Java and JavaScript provide a chord helper that makes the intent explicit and releases the modifiers afterwards.

Select all text in a field (Windows/Linux)
Selenium 4 Stable
WebElement editor = driver.findElement(By.id("notes"));
editor.sendKeys(Keys.chord(Keys.CONTROL, "a"));
editor.sendKeys(Keys.DELETE);
editor = driver.find_element(By.ID, "notes")
editor.send_keys(Keys.CONTROL, "a")
editor.send_keys(Keys.DELETE)
const editor = await driver.findElement(By.id('notes'));
await editor.sendKeys(Key.chord(Key.CONTROL, 'a'));
await editor.sendKeys(Key.DELETE);
var editor = driver.FindElement(By.Id("notes"));
editor.SendKeys(Keys.Control + "a");
editor.SendKeys(Keys.Delete);

The Actions API

Actions express key down and key up separately, which is clearer and is the only option for shortcuts that are not targeted at an input (a page-level Ctrl+K command palette, for example).

Page-level shortcut with Actions
Selenium 4 Stable
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("k")
.keyUp(Keys.CONTROL)
.perform();
ActionChains(driver) \
.key_down(Keys.CONTROL) \
.send_keys("k") \
.key_up(Keys.CONTROL) \
.perform()
await driver.actions()
.keyDown(Key.CONTROL)
.sendKeys('k')
.keyUp(Key.CONTROL)
.perform();
new Actions(driver)
.KeyDown(Keys.Control)
.SendKeys("k")
.KeyUp(Keys.Control)
.Perform();

Actions send keys to whichever element has focus. If nothing is focused, the keys go to the body. Click into the target first, or pass the element to sendKeys(element, ...), so you know where the input lands.

Platform-Aware Modifiers

macOS uses Command for copy, paste, select-all and most app shortcuts. A test that hard-codes CONTROL passes on Linux CI and fails on a developer’s Mac (or on a macOS cloud browser). Decide the modifier from the browser’s platform, not the machine running the test: with Selenium Grid or a cloud provider, the test runner may be Linux while the browser runs on macOS.

Choose Ctrl or Command based on the browser's platform
Selenium 4 Stable
Keys primaryModifier(WebDriver driver) {
Platform platform = ((HasCapabilities) driver).getCapabilities().getPlatformName();
return platform != null && platform.is(Platform.MAC) ? Keys.COMMAND : Keys.CONTROL;
}
Keys mod = primaryModifier(driver);
editor.sendKeys(Keys.chord(mod, "a"));
editor.sendKeys(Keys.chord(mod, "c"));
def primary_modifier(driver):
platform = (driver.capabilities.get("platformName") or "").lower()
return Keys.COMMAND if "mac" in platform else Keys.CONTROL
mod = primary_modifier(driver)
editor.send_keys(mod, "a")
editor.send_keys(mod, "c")
async function primaryModifier(driver) {
const caps = await driver.getCapabilities();
const platform = String(caps.getPlatform() || '').toLowerCase();
return platform.includes('mac') ? Key.COMMAND : Key.CONTROL;
}
const mod = await primaryModifier(driver);
await editor.sendKeys(Key.chord(mod, 'a'));
await editor.sendKeys(Key.chord(mod, 'c'));
string PrimaryModifier(IWebDriver driver)
{
var platform = (((IHasCapabilities)driver).Capabilities
.GetCapability("platformName")?.ToString() ?? "").ToLowerInvariant();
return platform.Contains("mac") ? Keys.Command : Keys.Control;
}
var mod = PrimaryModifier(driver);
editor.SendKeys(mod + "a");
editor.SendKeys(mod + "c");

If the capability is missing or ambiguous on your provider, ask the browser directly: navigator.platform (deprecated but universally present) or navigator.userAgentData.platform in Chromium browsers both work via executeScript.

Note: Not every shortcut maps one-to-one. Redo is Ctrl+Y on Windows but Cmd+Shift+Z on macOS; “go to line start” is Home on Windows and Cmd+Left on macOS. Keep a small table of shortcuts per platform in your test helpers rather than swapping only the modifier.

Copy and Paste: Verify Through the Page

The most reliable way to test copy and paste is to keep the clipboard round trip inside the browser: copy from one element, paste into another, and assert on the second element’s value. You never read the OS clipboard, so it works headless, on Grid, and on any OS.

Copy from one field and paste into another
Selenium 4 Stable
Keys mod = primaryModifier(driver);
WebElement source = driver.findElement(By.id("api-key"));
source.click();
source.sendKeys(Keys.chord(mod, "a"));
source.sendKeys(Keys.chord(mod, "c"));
WebElement target = driver.findElement(By.id("paste-target"));
target.click();
target.sendKeys(Keys.chord(mod, "v"));
assertEquals(source.getDomProperty("value"), target.getDomProperty("value"));
mod = primary_modifier(driver)
source = driver.find_element(By.ID, "api-key")
source.click()
source.send_keys(mod, "a")
source.send_keys(mod, "c")
target = driver.find_element(By.ID, "paste-target")
target.click()
target.send_keys(mod, "v")
assert target.get_property("value") == source.get_property("value")
const mod = await primaryModifier(driver);
const source = await driver.findElement(By.id('api-key'));
await source.click();
await source.sendKeys(Key.chord(mod, 'a'));
await source.sendKeys(Key.chord(mod, 'c'));
const target = await driver.findElement(By.id('paste-target'));
await target.click();
await target.sendKeys(Key.chord(mod, 'v'));
assert.strictEqual(await target.getAttribute('value'), await source.getAttribute('value'));
var mod = PrimaryModifier(driver);
var source = driver.FindElement(By.Id("api-key"));
source.Click();
source.SendKeys(mod + "a");
source.SendKeys(mod + "c");
var target = driver.FindElement(By.Id("paste-target"));
target.Click();
target.SendKeys(mod + "v");
Assert.That(target.GetDomProperty("value"), Is.EqualTo(source.GetDomProperty("value")));

If the page has no natural paste target, you can inject a temporary textarea, paste into it, read it, and remove it. That is a test-only helper, but it verifies what actually landed on the clipboard after the app’s “Copy” button was clicked.

Read what a Copy button put on the clipboard via a scratch textarea
Selenium 4 Medium
driver.findElement(By.cssSelector("[data-testid='copy-invite-link']")).click();
WebElement scratch = (WebElement) ((JavascriptExecutor) driver).executeScript(
"const t = document.createElement('textarea');" +
"t.id = '__clipboard_probe'; document.body.appendChild(t); return t;");
scratch.click();
scratch.sendKeys(Keys.chord(primaryModifier(driver), "v"));
String clipboard = scratch.getDomProperty("value");
((JavascriptExecutor) driver).executeScript("arguments[0].remove();", scratch);
assertTrue(clipboard.startsWith("https://app.example.com/invite/"));
driver.find_element(By.CSS_SELECTOR, "[data-testid='copy-invite-link']").click()
scratch = driver.execute_script(
"const t = document.createElement('textarea');"
"t.id = '__clipboard_probe'; document.body.appendChild(t); return t;")
scratch.click()
scratch.send_keys(primary_modifier(driver), "v")
clipboard = scratch.get_property("value")
driver.execute_script("arguments[0].remove();", scratch)
assert clipboard.startswith("https://app.example.com/invite/")
await driver.findElement(By.css("[data-testid='copy-invite-link']")).click();
const scratch = await driver.executeScript(
"const t = document.createElement('textarea');" +
"t.id = '__clipboard_probe'; document.body.appendChild(t); return t;");
await scratch.click();
await scratch.sendKeys(Key.chord(await primaryModifier(driver), 'v'));
const clipboard = await scratch.getAttribute('value');
await driver.executeScript('arguments[0].remove();', scratch);
assert.ok(clipboard.startsWith('https://app.example.com/invite/'));
driver.FindElement(By.CssSelector("[data-testid='copy-invite-link']")).Click();
var js = (IJavaScriptExecutor)driver;
var scratch = (IWebElement)js.ExecuteScript(
"const t = document.createElement('textarea');" +
"t.id = '__clipboard_probe'; document.body.appendChild(t); return t;");
scratch.Click();
scratch.SendKeys(PrimaryModifier(driver) + "v");
var clipboard = scratch.GetDomProperty("value");
js.ExecuteScript("arguments[0].remove();", scratch);
Assert.That(clipboard, Does.StartWith("https://app.example.com/invite/"));

Reading the Clipboard with the Async Clipboard API

Sometimes you want the clipboard contents directly, without a paste target. Browsers expose navigator.clipboard.readText(), which returns a Promise. WebDriver’s Execute Script command waits for a returned Promise to settle, so a plain executeScript call works.

The catch is permissions. readText() requires the clipboard-read permission (Chromium) and a focused document. Without them you get NotAllowedError or “Document is not focused”, surfaced in Selenium as a JavaScriptException.

Granting the permission in Chromium

Grant clipboard permissions, then read the clipboard (Chrome/Edge)
Selenium 4 Medium
// ChromiumDriver implements HasPermissions
((HasPermissions) driver).setPermission("clipboard-read", "granted");
((HasPermissions) driver).setPermission("clipboard-write", "granted");
driver.findElement(By.cssSelector("[data-testid='copy-invite-link']")).click();
String text = (String) ((JavascriptExecutor) driver)
.executeScript("return navigator.clipboard.readText();");
# Chromium only: uses a CDP command
driver.execute_cdp_cmd("Browser.grantPermissions", {
"permissions": ["clipboardReadWrite", "clipboardSanitizedWrite"],
"origin": "https://app.example.com",
})
driver.find_element(By.CSS_SELECTOR, "[data-testid='copy-invite-link']").click()
text = driver.execute_script("return navigator.clipboard.readText();")
// Chromium only: uses a CDP command
await driver.sendDevToolsCommand('Browser.grantPermissions', {
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
origin: 'https://app.example.com',
});
await driver.findElement(By.css("[data-testid='copy-invite-link']")).click();
const text = await driver.executeScript('return navigator.clipboard.readText();');
// Chromium only: uses a CDP command
((ChromiumDriver)driver).ExecuteCdpCommand("Browser.grantPermissions",
new Dictionary<string, object>
{
["permissions"] = new[] { "clipboardReadWrite", "clipboardSanitizedWrite" },
["origin"] = "https://app.example.com",
});
driver.FindElement(By.CssSelector("[data-testid='copy-invite-link']")).Click();
var text = (string)((IJavaScriptExecutor)driver)
.ExecuteScript("return navigator.clipboard.readText();");

The CDP-based calls are Chromium-only and tie you to DevTools. WebDriver BiDi has a permissions extension module that standardises this across browsers; check your binding’s BiDi documentation for whether it is exposed in your version before relying on it.

Firefox and Safari

Firefox supports navigator.clipboard.readText() in recent versions but shows a user-facing paste prompt rather than using a grantable permission, which an automated test cannot reliably dismiss. Safari has similar user-gesture requirements. For these browsers, use the scratch-textarea approach above.

Writing to the clipboard

To seed the clipboard before a paste test, navigator.clipboard.writeText("...") is more permissive than reading (it generally needs only focus and a secure context). It is a quick way to set up “paste a CSV into the grid” scenarios:

Seed the clipboard, then paste into the app
Selenium 4 Medium
((JavascriptExecutor) driver).executeScript(
"return navigator.clipboard.writeText(arguments[0]);", "Name\tQty\nWidget\t3");
WebElement grid = driver.findElement(By.cssSelector("[data-testid='bulk-grid'] [role='gridcell']"));
grid.click();
new Actions(driver).keyDown(primaryModifier(driver)).sendKeys("v").keyUp(primaryModifier(driver)).perform();
driver.execute_script("return navigator.clipboard.writeText(arguments[0]);", "Name\tQty\nWidget\t3")
cell = driver.find_element(By.CSS_SELECTOR, "[data-testid='bulk-grid'] [role='gridcell']")
cell.click()
mod = primary_modifier(driver)
ActionChains(driver).key_down(mod).send_keys("v").key_up(mod).perform()
await driver.executeScript('return navigator.clipboard.writeText(arguments[0]);', 'Name\tQty\nWidget\t3');
const cell = await driver.findElement(By.css("[data-testid='bulk-grid'] [role='gridcell']"));
await cell.click();
const mod = await primaryModifier(driver);
await driver.actions().keyDown(mod).sendKeys('v').keyUp(mod).perform();
((IJavaScriptExecutor)driver).ExecuteScript(
"return navigator.clipboard.writeText(arguments[0]);", "Name\tQty\nWidget\t3");
var cell = driver.FindElement(By.CssSelector("[data-testid='bulk-grid'] [role='gridcell']"));
cell.Click();
var mod = PrimaryModifier(driver);
new Actions(driver).KeyDown(mod).SendKeys("v").KeyUp(mod).Perform();

Headless and Remote Browsers

Clipboard behaviour is the area where headless and remote execution most often surprise people.

EnvironmentWhat happensRecommendation
Local headed browserUses the OS clipboard, shared with your desktopWorks, but tests can clobber (and read) your own clipboard; avoid running in parallel
Headless Chrome/EdgeCopy/paste via keyboard works inside the browser; async Clipboard API needs permissions and focusPrefer scratch-textarea verification
Linux CI with XvfbThe browser uses the virtual display’s clipboardParallel browsers on one display share a clipboard; isolate displays or avoid
Selenium Grid / cloudClipboard lives on the remote nodeYour test process cannot read it with OS libraries; verify through the page

Two rules follow from this table:

  1. Never read the clipboard with an OS library (java.awt.Toolkit, pyperclip, clipboardy, System.Windows.Forms.Clipboard) in a Selenium test. It reads the test machine’s clipboard, which is not the browser’s clipboard on Grid or in headless containers, and it is a shared global in parallel runs.
  2. Treat the clipboard as shared state. Two tests running in parallel in headed browsers on the same desktop will overwrite each other’s clipboard. Run clipboard tests serially or in isolated sessions.

Warning: Keyboard shortcuts handled by the browser itself, rather than the page, are often ignored under automation: Ctrl+T (new tab), Ctrl+W (close tab), Ctrl+L (address bar), Ctrl+P (print), and F5 in some drivers. WebDriver dispatches key events to the page, not to the browser UI. Use driver.switchTo().newWindow(), driver.close(), driver.navigate().refresh() and the print command instead.

Testing App-Defined Shortcuts

For shortcuts your application defines (Ctrl+S to save, ? for help, Ctrl+K for search), check three things:

  • The shortcut does what it should. Press it, wait for the observable result (toast, dialog, URL change), assert.
  • It works from the expected focus context. Many apps disable global shortcuts while focus is in an input. Test both focus states if that is part of the spec.
  • The browser default is prevented when it should be. If Ctrl+S opens your save flow, the browser’s “Save Page As” must not also fire. Under automation you cannot see the native dialog, so assert on the app behaviour and trust preventDefault coverage in unit tests.

Common Pitfalls

SymptomCauseFix
Select-all works on Linux, does nothing on MacHard-coded CONTROLChoose the modifier from the browser platform
Paste inserts nothingCopy happened while a different element had focusClick/focus the source before copying
NotAllowedError from readText()Missing permissionGrant clipboard-read (Chromium) or use a scratch textarea
“Document is not focused”Browser window not focused, common in parallel headed runsFocus the page; prefer page-based verification
Clipboard contains another test’s dataParallel tests sharing an OS clipboardSerialise clipboard tests or isolate sessions
Ctrl+T or Ctrl+W ignoredBrowser-UI shortcuts are not dispatchedUse WebDriver window commands
Modifier stuck down in later actionsActions chain with keyDown and no keyUpAlways pair keyDown with keyUp, or call releaseActions

Summary

  • Use chord or modifier-in-sendKeys for input shortcuts and the Actions API for page-level shortcuts.
  • Pick Ctrl or Command from the browser’s platform, not the test runner’s.
  • Verify copy and paste through the page whenever possible; it works everywhere.
  • Read the clipboard with navigator.clipboard.readText() only in Chromium with permissions granted.
  • Never use OS clipboard libraries in Selenium tests, and treat the clipboard as shared state in parallel runs.

Finished this lesson?

Mark it complete to track your progress through the course. Saved in this browser only.

Test yourself Actions & Interactions 10 questions · intermediate

Related lessons