User Agents

Web browsers and everyday web tech, explained

Inject JavaScript in Capybara Headless Chrome

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Add a prefs hash to enable performance logging or other settings if needed
  4. Common Mistakes
  5. Tips
  6. Troubleshooting
  7. Frequently Asked Questions

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

  1. 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:
    if (!window.injected) {
      window.injected = true;
      window.mockData = {};
      fetch = () => Promise.resolve({
        json: () => Promise.resolve({ success: true })
      });
    }
    Ensure it's self-contained and safe to run on any page.
  2. Read the JavaScript file in Ruby: You'll need to load the file's contents as a string. Use File.read with a relative path. For instance:
    js_content = File.read(Rails.root.join('spec', 'support', 'js', 'inject.js'))
    Place this in your test configuration or driver setup.
  3. Configure Capybara to use a custom Selenium driver: In your test setup (e.g., spec/rails_helper.rb or spec/support/capybara.rb), define a new driver that extends the default headless Chrome setup:
    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
    This creates a reusable driver configuration.
  4. Inject the JavaScript using before_each navigation: 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 a before block for JavaScript-enabled tests:
    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
    This runs the script once per test, after the page is loaded.
  5. Handle page reloads and navigation: If your test navigates between pages, the injected script is lost. Re-inject after each visit:
    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
    Alternatively, wrap navigation in a helper method that automatically injects the script.
  6. Set the default driver: Tell Capybara to use your new driver for JavaScript tests:
    Capybara.javascript_driver = :chrome_headless_with_js
    Capybara.current_driver = :chrome_headless_with_js
    Or use metadata like :js in RSpec to trigger it conditionally.
  7. Verify injection in tests: Add a simple check to confirm your script ran. For example, if your JS sets window.injected = true, verify it:
    it 'injects JavaScript' do
      visit '/'
      expect(page.evaluate_script('window.injected')).to be true
    end
    This ensures your setup is working.

Common Mistakes

  • Forgetting to re-inject after page navigation: JavaScript injected via execute_script does not persist across page loads. Always re-run it after visit or use a helper.
  • Using absolute paths incorrectly: Hardcoding file paths can break across environments. Use Rails.root.join or Pathname for portable paths.
  • Assuming injection happens before page scripts: Capybara’s execute_script runs after the page loads, so it cannot override scripts that run immediately on DOMContentLoaded.
  • Not handling file read errors: If the JS file is missing, File.read raises 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...rescue around File.read in 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.log in 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.