Skip to main content
SeleniumDecoded

Copy and Paste Text with Keyboard Shortcuts

Copy text from one field and paste it into another with Ctrl or Cmd shortcuts, pick the right modifier per OS, and test custom paste handlers reliably.

Medium Verified against Selenium 4.52.0

Problem

You need to test that pasting a 6-digit code into the first box of an OTP input fills all six boxes, or that copying a generated API key and pasting it elsewhere works. The test passes on your Mac and fails in Linux CI because Cmd+V does nothing there, and in some headless or remote setups the clipboard is not shared the way you expect.

Solution

Select and copy with keyboard shortcuts using a modifier chosen from the platform the browser runs on, then paste into the target. For testing a paste handler in isolation, dispatch a paste event with a DataTransfer instead of relying on the OS clipboard.

Copy from one field, paste into another
Selenium 4 Medium
// The modifier depends on where the BROWSER runs, not where the test code runs
Capabilities caps = ((HasCapabilities) driver).getCapabilities();
boolean mac = caps.getPlatformName() != null && caps.getPlatformName().is(Platform.MAC);
Keys mod = mac ? Keys.COMMAND : Keys.CONTROL;
WebElement source = driver.findElement(By.id("api-key"));
WebElement target = driver.findElement(By.id("confirm-key"));
source.click();
source.sendKeys(Keys.chord(mod, "a")); // select all
source.sendKeys(Keys.chord(mod, "c")); // copy
target.click();
target.sendKeys(Keys.chord(mod, "v")); // paste
assertEquals(source.getDomProperty("value"), target.getDomProperty("value"));
from selenium.webdriver.common.keys import Keys
# Modifier depends on where the BROWSER runs
mac = driver.capabilities.get("platformName", "").lower() in ("mac", "macos", "darwin")
mod = Keys.COMMAND if mac else Keys.CONTROL
source = driver.find_element(By.ID, "api-key")
target = driver.find_element(By.ID, "confirm-key")
source.click()
source.send_keys(mod, "a") # send_keys holds the modifier for the following key
source.send_keys(mod, "c")
target.click()
target.send_keys(mod, "v")
assert target.get_property("value") == source.get_property("value")
const caps = await driver.getCapabilities();
const mac = /mac|darwin/i.test(caps.getPlatform() || '');
const mod = mac ? Key.COMMAND : Key.CONTROL;
const source = await driver.findElement(By.id('api-key'));
const target = await driver.findElement(By.id('confirm-key'));
await source.click();
await source.sendKeys(Key.chord(mod, 'a'));
await source.sendKeys(Key.chord(mod, 'c'));
await target.click();
await target.sendKeys(Key.chord(mod, 'v'));
assert.strictEqual(await target.getAttribute('value'), await source.getAttribute('value'));
var platform = ((IHasCapabilities)driver).Capabilities.GetCapability("platformName")?.ToString() ?? "";
var mod = platform.Contains("mac", StringComparison.OrdinalIgnoreCase) ? Keys.Command : Keys.Control;
var source = driver.FindElement(By.Id("api-key"));
var target = driver.FindElement(By.Id("confirm-key"));
source.Click();
new Actions(driver).KeyDown(mod).SendKeys("a").SendKeys("c").KeyUp(mod).Perform();
target.Click();
new Actions(driver).KeyDown(mod).SendKeys("v").KeyUp(mod).Perform();
Assert.That(target.GetDomProperty("value"), Is.EqualTo(source.GetDomProperty("value")));

Testing a Paste Handler Without the Clipboard

If the behaviour under test is “what the app does on paste” (splitting an OTP across boxes, stripping formatting, rejecting images), you do not need the real clipboard. Dispatch the event the app listens for:

Dispatch a paste event with known data
Selenium 3 & 4 Stable
String PASTE = """
const [el, text] = arguments;
el.focus();
const dt = new DataTransfer();
dt.setData('text/plain', text);
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }));
""";
((JavascriptExecutor) driver).executeScript(PASTE, driver.findElement(By.cssSelector(".otp input")), "482913");
PASTE = """
const [el, text] = arguments;
el.focus();
const dt = new DataTransfer();
dt.setData('text/plain', text);
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }));
"""
driver.execute_script(PASTE, driver.find_element(By.CSS_SELECTOR, ".otp input"), "482913")
const PASTE = `
const [el, text] = arguments;
el.focus();
const dt = new DataTransfer();
dt.setData('text/plain', text);
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }));`;
await driver.executeScript(PASTE, await driver.findElement(By.css('.otp input')), '482913');
const string Paste = """
const [el, text] = arguments;
el.focus();
const dt = new DataTransfer();
dt.setData('text/plain', text);
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }));
""";
((IJavaScriptExecutor)driver).ExecuteScript(Paste, driver.FindElement(By.CssSelector(".otp input")), "482913");

This is deterministic, parallel-safe and works headless. The trade-off: it does not insert text by default, so it only suits apps that handle paste themselves (which OTP and rich-text components do).

Why It Works

Keyboard shortcuts are interpreted by the browser on the machine where it runs, so the modifier must match that machine’s OS: on a Linux Grid node it is Ctrl, even if your laptop is a Mac. Selecting all before copying makes the copy independent of where the caret was. Comparing values afterwards proves the round trip actually happened.

Gotchas

  • Parallel tests share one OS clipboard when they run on the same machine without isolation. Two tests copying at once can paste each other’s text. Prefer the dispatched-event approach, or run clipboard tests serially.
  • Reading the clipboard from JavaScript (navigator.clipboard.readText()) needs a permission and a focused, secure page; it is unreliable in automation. Assert on the pasted field instead.
  • Headless and remote browsers may have no system clipboard or an isolated one. If copy/paste silently does nothing in CI but works locally, this is usually why.
  • “Copy” buttons that use navigator.clipboard.writeText can be verified by pasting into a scratch input on the same page, as above.
  • Modifiers in send keys are sticky. Within a single element send-keys call, a modifier stays pressed until the end of that call (or until Keys.NULL). send_keys(mod, "a", "hello") sends Ctrl+A and then Ctrl+H, Ctrl+E… Keep one shortcut per call, as above.

Learn the theory