Inject JavaScript in Capybara Headless Chrome
In this article
Injecting a JavaScript file into Capybara headless Chrome allows you to extend or modify page behavior during automated browser tests. This technique is useful for mocking APIs, overriding browser features, adding helper functions, or simulating user interactions not easily achievable through standard Capybara commands. The process involves configuring Chrome to execute custom JavaScript before any page content loads, ensuring your script runs in every test session. This guide walks through how to set this up reliably in a Rails or Ruby testing environment using Capybara with Selenium and headless Chrome.
What You'll Need
- Ruby on Rails or Ruby project with Capybara and Selenium WebDriver
- ChromeDriver installed and accessible in your system PATH
- A JavaScript file you want to inject (e.g.,
mock-api.js) - Basic knowledge of RSpec or another test framework using Capybara
Step-by-Step
- Create your JavaScript file: Save the JavaScript you want to inject into a file, such as
spec/support/js/inject.js. This could contain mocks, utility functions, or overrides. For example:
Ensure it's self-contained and safe to run on any page.if (!window.injected) { window.injected = true; window.mockData = {}; fetch = () => Promise.resolve({ json: () => Promise.resolve({ success: true }) }); } - Read the JavaScript file in Ruby: You'll need to load the file's contents as a string. Use
File.readwith a relative path. For instance:
Place this in your test configuration or driver setup.js_content = File.read(Rails.root.join('spec', 'support', 'js', 'inject.js')) - Configure Capybara to use a custom Selenium driver: In your test setup (e.g.,
spec/rails_helper.rborspec/support/capybara.rb), define a new driver that extends the default headless Chrome setup:
This creates a reusable driver configuration.Capybara.register_driver :chrome_headless_with_js do |app| options = Selenium::WebDriver::Chrome::Options.new options.add_argument('--headless') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument('--disable-gpu') options.add_argument('--window-size=1920,1080')Add a prefs hash to enable performance logging or other settings if needed
prefs = { 'profile.managed_default_content_settings.images' => 2 } options.add_preference(:prefs, prefs) Capybara::Selenium::Driver.new(app, browser: :chrome, options: options) end - Inject the JavaScript using
before_eachnavigation: Since ChromeDriver doesn’t support direct injection of persistent JS across pages, use Capybara’s session to execute the script right after page loads. The most reliable method is to run the script in abeforeblock for JavaScript-enabled tests:
This runs the script once per test, after the page is loaded.config.before(:each, :js) do if page.driver.browser.respond_to?(:execute_script) js_content = File.read(Rails.root.join('spec', 'support', 'js', 'inject.js')) page.execute_script(js_content) end end - Handle page reloads and navigation: If your test navigates between pages, the injected script is lost. Re-inject after each visit:
Alternatively, wrap navigation in a helper method that automatically injects the script.After do if @last_injected_js != js_content page.execute_script(js_content) if page.driver.browser.respond_to?(:execute_script) @last_injected_js = js_content end end - Set the default driver: Tell Capybara to use your new driver for JavaScript tests:
Or use metadata likeCapybara.javascript_driver = :chrome_headless_with_js Capybara.current_driver = :chrome_headless_with_js:jsin RSpec to trigger it conditionally. - Verify injection in tests: Add a simple check to confirm your script ran. For example, if your JS sets
window.injected = true, verify it:
This ensures your setup is working.it 'injects JavaScript' do visit '/' expect(page.evaluate_script('window.injected')).to be true end
Common Mistakes
- Forgetting to re-inject after page navigation: JavaScript injected via
execute_scriptdoes not persist across page loads. Always re-run it aftervisitor use a helper. - Using absolute paths incorrectly: Hardcoding file paths can break across environments. Use
Rails.root.joinorPathnamefor portable paths. - Assuming injection happens before page scripts: Capybara’s
execute_scriptruns after the page loads, so it cannot override scripts that run immediately onDOMContentLoaded. - Not handling file read errors: If the JS file is missing,
File.readraises an error. Ensure the file exists or wrap in error handling during test setup.
Tips
- Wrap repeated injection logic in a module or helper method to avoid duplication.
- Use
begin...rescuearoundFile.readin test helpers to fail gracefully if the file is missing. - Minimize the injected script size to avoid performance issues in headless mode.
- Use feature flags in your JS (like
window.injected) to prevent duplicate execution. - Log to
console.login your injected JS and capture browser logs for debugging.
Troubleshooting
If the script does not appear to run, first verify the file is being read correctly by adding a puts js_content in your setup. Then check that page.execute_script is being called after visit. If tests hang, ensure ChromeDriver version matches your Chrome version. Use page.driver.browser.logs.get(:browser) to inspect console errors. If the script modifies global objects but has no effect, confirm it’s not being blocked by Content Security Policy (CSP) — headless Chrome enforces CSP strictly. In such cases, consider relaxing CSP in test environments or using --disable-web-security (not recommended for production-like environments).
Frequently Asked Questions
Can I inject JavaScript before any page content loads?
No, Capybara’s execute_script runs after the page is loaded. For true pre-load injection, you’d need a browser extension or proxy, which is not supported in standard headless Chrome setups.
Does this work with Turbolinks or SPAs?
Yes, but you must re-inject after each Turbolinks navigation or SPA route change, as the page context resets.
Can I inject multiple JavaScript files?
Yes. Read and concatenate multiple files in Ruby before passing the combined string to execute_script.
Is this method thread-safe in parallel tests?
Yes, as each test runs in an isolated browser session. Just ensure file reads don’t conflict (e.g., no file writing during tests).
Why use headless mode instead of visible Chrome?
Headless is faster and runs on CI/CD servers without a GUI. The injection process is identical in both modes.
Can I use this to mock localStorage?
Yes. Your injected script can override localStorage or sessionStorage with mock implementations for consistent test behavior.