Free tools Windows power users keep installed

One-click scans. No signup required.

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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To inject a local JavaScript file into a Capybara test running in headless Chrome, use a JavaScript-capable driver, read the file in Ruby, and pass its contents to page.execute_script:

script_path = Rails.root.join('spec', 'support', 'scripts', 'helper.js')
page.execute_script(File.read(script_path))

File.read happens in the Ruby test process. Capybara then sends the resulting source to the browser. This executes the code in the current document; it is not a pre-page-load hook.

1. Use a JavaScript-capable Capybara driver

Capybara’s default :rack_test driver does not execute JavaScript. Configure a Selenium-backed driver such as :selenium_chrome_headless, or another driver that supports browser JavaScript. Capybara lists Selenium Chrome headless among its drivers, and Selenium documents JavaScript execution in headless Chrome.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Capybara.configure do |config|
  config.default_driver = :selenium_chrome_headless
end

Your project also needs compatible versions of the capybara gem, selenium-webdriver, Chrome, and ChromeDriver. Compatibility is environment-dependent, so check the versions installed in your test environment rather than assuming a particular combination.

#1 Best Overall
Lexar D40E 128GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty

2. Inject a local file into the current page

The normal pattern is to resolve the file path in Ruby, read it as text, and execute that text through the page session.

script_path = Rails.root.join('spec', 'support', 'scripts', 'helper.js')
source = File.read(script_path)
page.execute_script(source)

For a non-Rails project, use any Ruby path that points to the fixture:

script_path = File.expand_path('../support/scripts/helper.js', __dir__)
page.execute_script(File.read(script_path))

Capybara’s session-level execute_script accepts JavaScript source and does not return a value. The API is documented in the Capybara session implementation.

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

Example spec

RSpec.describe 'checkout helper', type: :system, js: true do
  it 'runs the helper in Chrome' do
    visit '/checkout'

    script_path = Rails.root.join('spec', 'support', 'scripts', 'helper.js')
    page.execute_script(File.read(script_path))

    expect(page).to have_css('[data-helper-ready="true"]')
  end
end

The visit call creates the document. Inject after navigation has reached the page on which the script is needed.

3. Make the injection timing match the script

execute_script runs against the current document when called. Timing therefore depends on what the file expects.

When the script only defines functions

Inject after visit. You can call the functions later from another script or interact with the page normally.

When it needs application globals

Wait until the application has created those globals. For example, use a Capybara assertion for a visible element or a test-specific readiness marker before injecting. Do not rely on a fixed sleep unless the application has no observable condition; sleeps make tests slower and still race under load.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
SANDISK 128GB Ultra Flair, USB-A Flash Drive, Up to 150MB/s Read Speeds
  • High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
  • Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
  • Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
  • Sleek, durable metal casing
  • Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]

When it modifies existing DOM nodes

Inject after the relevant nodes exist. A script that queries #results immediately will fail or do nothing if the page has not rendered that element yet.

When it installs event listeners

Inject before the user action that should trigger the listener, but after the document and any required framework objects are available.

4. Loading a script by URL instead of reading it in Ruby

If the browser should load a served resource, append a <script src> element from JavaScript:

page.execute_script(<<~JS)
  const script = document.createElement('script');
  script.src = '/assets/helper.js';
  document.head.appendChild(script);
JS

This assumes /assets/helper.js resolves from the page's origin and is actually served there. A path that exists only on the test runner, such as /Users/me/project/helper.js, is not a browser URL. For a cross-origin URL, content-security policy, same-origin rules, CORS behavior, or the test server configuration can prevent loading.

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

Appending a script element is a DOM implementation of dynamic loading; it is different from passing source to Capybara. If you need to know when an external file has loaded, have the file set a marker or dispatch an event and wait for that condition in the test.

5. Choose the right Capybara API

API or method Use it when Important constraint
page.execute_script(source) You need to run JavaScript and do not need a result Runs in the current document; the file must be read by Ruby first
page.evaluate_script(expression) You need the value produced by an expression Returned values can vary by driver
Element-level execute_script The operation intentionally belongs to one element The element is used as this; it is not equivalent to page-level execution
Pre-document or CDP registration The code must run before page scripts or on every navigation The exact Ruby API and guarantees depend on your Capybara, Selenium, Chrome, and ChromeDriver versions

Use evaluate_script when a returned value matters:

title = page.evaluate_script('document.title')
expect(title).to eq('Checkout')

Capybara documents argument support, but the accepted argument types are determined by the selected driver. Do not assume that objects accepted by one driver will serialize identically in another.

6. A complete reusable helper

Centralizing file injection keeps specs short and makes path errors easier to diagnose.

Rank #3
2 Pack 64GB USB Flash Drive USB 2.0 Thumb Drives Jump Drive Fold Storage Memory Stick Swivel Design - Black
  • What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
  • Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
  • Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
  • Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
  • Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers
module JavascriptFixtures
  def inject_javascript_file(relative_path)
    path = Rails.root.join('spec', 'support', 'scripts', relative_path)
    raise "JavaScript fixture not found: #{path}" unless File.file?(path)

    page.execute_script(File.read(path))
  end
end

RSpec.configure do |config|
  config.include JavascriptFixtures, type: :system
end

Use it in a system spec:

visit '/dashboard'
expect(page).to have_css('[data-dashboard]')
inject_javascript_file('helper.js')

Reading the file before calling Capybara also lets Ruby report a clear missing-file error instead of sending an invalid value to the driver.

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

7. Troubleshooting common failures

“JavaScript is not running” or no DOM change occurs

Cause: The session is using :rack_test, which does not execute JavaScript.

Fix: Mark the test for JavaScript where your test framework requires it and select Selenium Chrome headless or another JavaScript-capable driver.

The browser receives a path rather than code

Cause: A filesystem path was passed to execute_script.

Fix: Read the path in Ruby:

page.execute_script(File.read('/absolute/path/to/helper.js'))

The file is not found

Cause: The relative path is resolved from an unexpected working directory, or the Rails root differs from the assumed project root.

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

Fix: Build an absolute path with Rails.root.join or File.expand_path, then check File.file?(path) before injection.

The script runs but cannot find an element

Cause: Injection happened before the application rendered the target node.

Rank #4
SIMMAX 32GB Memory Stick USB 2.0 Flash Drives Swivel Thumb Drive Pen Drive (32GB Purple)
  • GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
  • BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
  • EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
  • TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
  • WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.

Fix: Navigate first and wait for a meaningful application condition, such as expect(page).to have_css('#results'), then inject.

The script expects a global that is undefined

Cause: The application has not initialized the global, or the script is running on a different page.

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

Fix: Verify the URL and wait for the initialization marker. If the global is created by a module bundle, confirm that the bundle has loaded before injection.

You expected a return value from execute_script

Cause: execute_script is for execution without a returned result.

Fix: Use evaluate_script for an expression whose value you need.

Element and page execution behave differently

Cause: Element-level execution binds this to the element.

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

Fix: Use page.execute_script for code that expects document, page-level globals, or a document-wide context.

Best Value
Sale
IMEASON Swivel Design 16GB USB Flash Drive with Keychain, USB 2.0 Portable Thumb Drive Memory Stick, FAT32 Format Flashdrive for Data Storage, Photos, Music, Files (Black, 16 GB)
  • 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
  • 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
  • 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
  • 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
  • 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.

Dynamic script.src loading fails

Cause: The URL is not reachable from the browser, the asset is not served, or browser page policy blocks it.

Fix: Open the URL in the test browser's context, verify the test server route, use a same-origin asset where practical, and inspect browser logs or network requests.

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

8. Current-document injection versus pre-load injection

These are separate requirements. The file-reading recipe runs only after a document exists and only when your test calls it. It does not guarantee execution before application scripts, and it does not automatically repeat on every navigation.

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.

If your test requires code before page scripts or on every navigation, investigate a version-specific Selenium or Chrome DevTools Protocol setup for the exact versions in your project. The portable Capybara API documented here does not establish a universal preload command or guarantee. Avoid presenting an unverified CDP snippet as interchangeable with page.execute_script.

9. Reliability, performance, and security considerations

  • Keep fixtures deterministic: avoid scripts that depend on wall-clock timing, random values, or external network services unless those dependencies are part of the test.
  • Inject once per document: repeated injection can register duplicate event listeners or redefine globals. Add an idempotence guard if a test may call the helper more than once.
  • Prefer observable readiness: assertions about rendered state are more reliable than arbitrary delays.
  • Keep secrets out of fixtures: code injected into a browser test can access page data. Do not embed production credentials or tokens.
  • Watch large files: every injection transfers the source from Ruby to the browser. Keep helper fixtures focused, especially in large suites.
  • Reset between navigations: a new document does not retain JavaScript state from the previous page.

Or skip the browser setup

If your actual goal is to obtain a clean image or PDF of a page rather than exercise JavaScript inside a Capybara test, ScreenshotNeo provides a single HTTP request. Its API can run custom JavaScript and CSS, wait for a selector, delay, or network idle, and capture a full page, element, image, or PDF. Documentation and parameter details are at screenshotneo.com/docs/.

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

Before capture, ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server includes take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Does Capybara execute a JavaScript file path directly?

No. Read the file in Ruby with File.read, then pass the resulting source string to page.execute_script.

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

Can this method run before the page loads?

No. It runs in the current document when called. Pre-document execution requires a version-specific Selenium or Chrome DevTools setup.

Which driver should I use for headless Chrome?

Use a JavaScript-capable Selenium driver, such as Capybara's :selenium_chrome_headless, with compatible Chrome and WebDriver components.

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.