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

In JavaScript Selenium tests, pass ordinary strings to WebElement.sendKeys(), then read an input with getAttribute('value') or read rendered text with getText(). Await each Selenium command before asserting its result. The distinction matters: an input’s value is not the same thing as an element’s visible text.

Enter a string into a Selenium element

With the Node.js Selenium WebDriver binding, a string is an ordinary JavaScript value. Locate a keyboard-interactable element, clear it if you want to replace existing content, and send the string:

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

sendKeys() is asynchronous, so await it before reading the result or making an assertion. It types into keyboard-interactable elements, typically text inputs and content-editable elements; it is not a universal way to set text on any page element. An element that cannot accept keyboard input may produce an error. See the Selenium JavaScript WebElement API and the element interactions guide.

Decide whether to clear first

Call clear() when the test should replace the field’s existing contents. Leave it out when the intended scenario is appending text to whatever is already present. This choice is part of the test behavior, not just setup.

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 back the right kind of string

For a form control, read its value. For text rendered by an element, use getText():

const inputValue = await field.getAttribute('value');
assert.strictEqual(inputValue, 'Hello, Selenium');

const rendered = await driver.findElement(By.id('result')).getText();
assert.strictEqual(rendered, 'Hello, Selenium');

getText() returns visible inner text, including text in sub-elements, and removes leading and trailing whitespace. That behavior makes it appropriate for visible page content, but not for checking what a text input contains. For inputs, assert the value attribute instead. The Selenium JavaScript API documents both methods and its examples read an input’s value after typing.

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.

Assert exact strings or locale-aware matches

assert.strictEqual(actual, expected) checks exact, case-sensitive equality. Use it when capitalization and every character are part of the expected behavior. Do not silently trim, normalize, or change case unless the product requirement calls for that transformation; doing so can make a test pass despite a real difference.

When case-insensitive comparison is required

For locale-aware case-insensitive matching, JavaScript’s Intl.Collator or localeCompare() with an appropriate sensitivity option is more robust than blindly converting both strings to upper- or lowercase. Choose the locale and comparison sensitivity to match the application’s requirements. See MDN’s JavaScript String reference.

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.
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.

Handle special keys and keyboard shortcuts

Use Selenium’s Key constants or the Actions API for keys that are not ordinary text. For example, the keyboard actions guide demonstrates pressing Shift while entering a letter, then releasing Shift. A modifier can remain active until it is released or reset with Key.NULL, so make the intended key state explicit.

const { Key } = require('selenium-webdriver');

await driver.actions()
  .keyDown(Key.SHIFT)
  .sendKeys('a')
  .keyUp(Key.SHIFT)
  .perform();

Keyboard shortcut modifiers can depend on the operating system. Selenium’s example uses Command on macOS and Control on other platforms; select the modifier appropriate to the environment in which the test runs. See the official Selenium keyboard actions guide.

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

Account for Unicode and what “character” means

JavaScript strings use UTF-16 code units. A string’s length and indexed positions count code units, not necessarily user-perceived characters. Iterating a string yields Unicode code points, but a code point can still be only one part of a visible grapheme, such as an emoji combined with a modifier or another emoji.

  • For ordinary exact string equality, compare the strings directly.
  • For limits defined in UTF-16 code units, length may be the relevant measure.
  • For code-point counts, iterate the string rather than splitting it into individual UTF-16 units.
  • For user-perceived character limits, use a grapheme-aware definition; neither length nor spread syntax necessarily counts visible graphemes.

Avoid split('') when processing arbitrary Unicode: it can separate the two code units of a surrogate pair. Lone surrogates are also an edge case when a string crosses into an API that expects valid UTF-16 or UTF-8 data. MDN documents isWellFormed() and toWellFormed() for detecting and sanitizing such strings, and notes that encodeURI() can throw a URIError for a lone surrogate. Only sanitize if that matches the behavior the application is meant to test.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use page-side JavaScript only when it is the behavior under test

Selenium’s executeScript() runs JavaScript in the selected browser frame or window. It is useful when a test specifically needs a page-side computation. For normal user-like typing and reading, prefer element methods such as sendKeys(), getAttribute('value'), and getText(); they test the interaction path rather than assigning or inspecting data through a separate mechanism.

executeAsyncScript() has a different completion contract: the injected script must invoke Selenium’s callback to signal completion. Consult the Selenium JavaScript API for the installed binding’s details.

Troubleshoot string assertion failures

  • The input assertion returns an unexpected value: Check that you read getAttribute('value'), not getText(). A form control’s entered content is its value.
  • The visible-text assertion differs only in whitespace: Selenium’s getText() removes leading and trailing whitespace. Confirm whether the requirement concerns normalized visible text or an exact input value.
  • sendKeys() fails or types nowhere: Verify that the located element is keyboard-interactable, such as a text field or content-editable element, and that it is in a state that accepts keyboard input.
  • The assertion runs before typing finishes: Await sendKeys() and the subsequent read method before asserting. Selenium’s JavaScript commands are asynchronous.
  • Later keystrokes behave as though Shift is still held: Explicitly call keyUp() for the modifier, or reset modifier state with Key.NULL where appropriate.
  • A shortcut works on one operating system but not another: Account for the platform modifier; Command is used on macOS in Selenium’s example, while Control is used elsewhere.
  • Unicode length checks disagree with what a person sees: Identify whether the requirement counts UTF-16 code units, code points, or grapheme clusters before choosing a counting method.

Or skip the browser setup

For capturing a website rather than testing string entry, ScreenshotNeo provides a screenshot API and MCP server. Its one-call API can return a screenshot or PDF; see the ScreenshotNeo documentation.

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

ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; these steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server lets AI agents use screenshot tools. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for 1,000 free screenshots a month, with no card.

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

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.