Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk6 min

How to Work With Strings in JavaScript Selenium Tests

Use Selenium’s JavaScript binding to type and assert strings correctly: await sendKeys, read input values separately from visible text, and handle modifiers and Unicode deliberately.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Selenium’s Node.js WebDriver binding, pass ordinary JavaScript strings to sendKeys(), then read the right representation back: use an input’s value for form fields and getText() for visible page text. Await each WebDriver command before asserting. For special keys, use Selenium’s key constants or Actions API and release modifiers explicitly.

Enter and verify a string in a form field

Locate a keyboard-interactable control, clear it when the test should replace existing content, type the expected string, and read its value before asserting. Selenium documents sendKeys() as an asynchronous WebElement command, so await it and the subsequent read.

const { Builder, By } = require('selenium-webdriver');
const assert = require('node:assert/strict');

(async () => {
  const driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.get('https://example.com/form');

    const field = await driver.findElement(By.name('message'));
    await field.clear();
    const expected = 'Hello, Selenium!';
    await field.sendKeys(expected);

    const actual = await field.getAttribute('value');
    assert.equal(actual, expected);
  } finally {
    await driver.quit();
  }
})();

Replace the example URL and locator with the page and control under test. This CommonJS example assumes the Selenium JavaScript package is installed and a compatible Chrome browser and driver are available to the environment. Use the browser configuration appropriate to your project if you do not run Chrome.

  • clear() matters when the field may already contain a value; omit it only when appending is the behavior being tested.
  • sendKeys() simulates keyboard input. It is intended for keyboard-interactable elements such as text inputs and content-editable regions, not arbitrary elements. An element that cannot receive keyboard input may produce an error.
  • Await commands in sequence. Reading immediately after starting sendKeys() can make a test observe the old value.

The Selenium JavaScript WebElement API and interaction guide document these behaviors: WebElement API and element interactions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Read the representation the page actually displays

An input’s contents are its value; they are not ordinarily the element’s visible inner text. For rendered text in a result, label, or other page element, use getText(). Selenium describes getText() as returning visible inner text, including text from child elements, while trimming leading and trailing whitespace.

const field = await driver.findElement(By.name('message'));
await field.clear();
await field.sendKeys(expected);
assert.equal(await field.getAttribute('value'), expected);

const rendered = await driver.findElement(By.id('result')).getText();
assert.equal(rendered, expected);

If an assertion fails, first check whether it queried a form value or visible text. Also check whether the application transforms, formats, or delays updating the displayed value; wait for the page’s expected state before reading it rather than treating every mismatch as a string-comparison defect.

Test special keys and keyboard shortcuts

For keys that are not ordinary text, use Selenium’s Key constants. For a held modifier or a more involved sequence, use the Actions API. Modifiers remain active until released or reset, so make their release part of the test.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
const { Key } = require('selenium-webdriver');

const field = await driver.findElement(By.name('message'));
await field.clear();
await field.sendKeys(Key.SHIFT, 'hello', Key.NULL);
assert.equal(await field.getAttribute('value'), 'HELLO');

Key.NULL resets modifier state. Alternatively, use Actions to make the press and release explicit:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await driver.actions()
  .keyDown(Key.SHIFT)
  .sendKeys('a')
  .keyUp(Key.SHIFT)
  .perform();

Shortcut modifiers depend on the operating system. Selenium’s keyboard example uses Command on macOS and Control on other platforms; select the key for the platform on which the test runs rather than assuming one shortcut works everywhere. See the Selenium keyboard actions guide for the documented JavaScript patterns.

Choose string equality and character counting deliberately

For exact matching, ordinary JavaScript equality is case-sensitive. Compare the exact value when that is what the application requirement specifies. Do not normalize, trim, or change case simply to make an assertion pass: each transformation changes what the test verifies.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

If the requirement is locale-aware, case-insensitive comparison, use Intl.Collator or localeCompare() with an appropriate sensitivity option instead of assuming that uppercasing or lowercasing handles every language. The right locale and comparison settings depend on the product requirement.

JavaScript string length and indexes count UTF-16 code units, not necessarily the characters a person sees. Iterating a string yields Unicode code points, but a visible grapheme can contain multiple code points, as with joined or modified emoji. split('') can separate the two code units of a surrogate pair. If the application enforces a character limit, define whether it means code units, code points, or user-perceived grapheme clusters, then make the test measure that same unit. MDN explains these distinctions in its JavaScript String reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For systems that accept arbitrary Unicode or pass strings to URI or UTF-8 encoding APIs, malformed lone surrogates are another edge case. MDN documents isWellFormed() and toWellFormed() for detection and sanitization, and notes that encodeURI() can throw a URIError for such strings. Test this only if malformed input is relevant to the application’s behavior.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Use page-side JavaScript only when the test needs it

executeScript() runs JavaScript in the currently selected browser frame or window. It can be useful for a page-side computation or inspection that element interactions do not express well. For normal user-like typing and reading, prefer sendKeys(), getAttribute('value'), and getText() so the test exercises the element interaction path.

Selenium’s executeAsyncScript() has a different completion rule: the injected script must call its provided callback to signal completion. Use it only when that asynchronous page-side behavior is needed, and ensure every completion path calls the callback. See the JavaScript WebElement API and your installed binding’s driver API documentation for the version-specific script method signature.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot string assertions

  • The assertion reads an empty or old value: await sendKeys() before reading. Confirm that the locator targets the intended control and that the element is ready to receive input.
  • The input assertion does not match, but the page looks right: read the input’s value, not its getText(). For a rendered result, use getText().
  • sendKeys() fails: confirm the element is keyboard-interactable and in a state that accepts input. A generic container is not necessarily a valid typing target.
  • Later typing behaves as if Shift or another modifier is still held: release it with keyUp() or reset modifier state with Key.NULL.
  • A shortcut works on one operating system but not another: account for platform-specific Command versus Control behavior in the test configuration.
  • An emoji length assertion is surprising: determine whether the application counts UTF-16 code units, code points, or grapheme clusters; JavaScript’s length is not a visible-character count.
  • A URI operation rejects a string: check for lone surrogates if the application accepts arbitrary Unicode, and decide whether rejecting or sanitizing malformed input is the intended behavior.

These examples follow the Selenium JavaScript binding documentation available as accessed October 3, 2026. Method signatures and browser or platform keyboard behavior can change; consult the documentation matching the binding version installed in your project when version-specific behavior matters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Or skip the browser setup

If the task is to capture a page rather than exercise its inputs, ScreenshotNeo can return a screenshot from one GET request. For example, using cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for setup and request options. Before capture it accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

Sign up for 1,000 free screenshots a month with no card.

Frequently Asked Questions

Does sendKeys() set a field’s value directly?

No. It sends keyboard input to a keyboard-interactable element; use it when the test should exercise typing.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use getText() to read an input?

No. Read a form control’s value; reserve getText() for visible rendered text.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.