ScreenshotNeo

BlogHow-to

How to Load JavaScript from a String in Ruby

Run JavaScript stored in Ruby strings with ExecJS or MiniRacer, choose the right runtime, handle errors, and avoid common deployment traps.

By the ScreenshotNeo team30 September 20261 min read

How to Load JavaScript from a String in Ruby

Direct answer: Ruby cannot execute JavaScript with its own eval. A Ruby string containing JavaScript must be passed to a JavaScript runtime. The two documented Ruby options are ExecJS, which gives your application a common interface over an installed runtime, and MiniRacer, which embeds V8 in your Ruby process. Use ExecJS.eval for a one-off expression, ExecJS.compile for reusable functions, or a persistent MiniRacer::Context when you specifically want embedded V8.

What “load JavaScript from a string” means

There are two different operations that are often confused:

A Ruby string must cross into a JavaScript runtime before it can be evaluated.
A Ruby string must cross into a JavaScript runtime before it can be evaluated.
  1. Evaluate an expression: execute source such as "'red yellow blue'.split(' ')" and receive the result in Ruby.
  2. Load a program into a context: define functions or variables once, then call them repeatedly.

Ruby’s Kernel#eval evaluates Ruby expressions in a string and optionally a Ruby binding; it does not parse JavaScript. See the Ruby Kernel reference for the Ruby behavior.

Option 1: ExecJS

ExecJS lets you run JavaScript code from Ruby through a common API. Install the gem:

gem install execjs

In a Bundler project, add gem "execjs" to your Gemfile and run bundle install. ExecJS detects an available runtime. Its README lists Node.js, Bun, JavaScriptCore, Windows Script Host/JScript, Duktape, Rhino, V8/MiniRacer, and GraalVM JavaScript; the actual choice depends on your environment.

Evaluate one expression

require "execjs"

javascript = "'red yellow blue'.split(' ')"
result = ExecJS.eval(javascript)

p result
# ["red", "yellow", "blue"]

ExecJS.eval is convenient when the source is short and you only need one return value. The final JavaScript expression becomes the result. If the source contains statements, make the final expression explicit.

require "execjs"

source = <<~JS
  var first = 20;
  var second = 22;
  first + second;
JS

puts ExecJS.eval(source)
# 42

Compile once and call functions

For a library or a function used more than once, compile a context instead of reparsing the source on every call:

require "execjs"

source = <<~JS
  function add(a, b) {
    return a + b;
  }

  function slugify(value) {
    return value.toLowerCase().replace(/[^a-z0-9]+/g, "-")
      .replace(/^-|-$/g, "");
  }
JS

context = ExecJS.compile(source)
puts context.call("add", 20, 22)
puts context.call("slugify", "Hello, Ruby!")
# 42
# hello-ruby

Arguments passed to context.call are converted to JavaScript values. Keep boundaries simple: strings, numbers, booleans, arrays, hashes, and nil map predictably. For complex objects, serialize to JSON and parse inside JavaScript.

Selecting a runtime

Runtime behavior and JavaScript feature support vary. You can inspect the selected runtime:

require "execjs"

puts ExecJS.runtime.name

To request a particular runtime, assign ExecJS.runtime using the runtime adapter available in your installation, or set the EXECJS_RUNTIME environment variable as documented by ExecJS. Verify the runtime exists in production; a laptop with Node.js installed and a minimal container without it will behave differently.

Option 2: MiniRacer and an embedded V8 context

MiniRacer embeds V8 directly in Ruby. Add gem "mini_racer" to your Gemfile and bundle it, then create a context:

require "mini_racer"

context = MiniRacer::Context.new
context.eval("var adder = (a, b) => a + b;")

result = context.eval("adder(20, 22)")
puts result
# 42

A context persists variables and functions between calls. This is useful for loading a JavaScript library once and processing many inputs:

require "mini_racer"

context = MiniRacer::Context.new
context.eval(<<~JS)
  function normalizeEmail(value) {
    return value.trim().toLowerCase();
  }
JS

%w[ Alice@EXAMPLE.COM  bob@example.com ].each do |email|
  puts context.call("normalizeEmail", email)
end

MiniRacer documents controls for context timeouts, a memory soft limit, filename information in stack traces, and attaching Ruby functions to JavaScript. Check its supported Ruby and platform matrix and current release notes before choosing it for a deployment target.

ExecJS or MiniRacer?

Requirement Better starting point Reason
Portability across installed engines ExecJS It presents one API over multiple runtimes.
One short expression ExecJS ExecJS.eval is minimal.
Reusable compiled source Either ExecJS contexts and MiniRacer contexts both retain loaded code.
Embedded V8 specifically MiniRacer V8 runs inside the Ruby process.
Documented V8 resource controls MiniRacer Timeout and memory options are part of its API.

ExecJS intentionally exposes a lowest-common-denominator interface. Its documentation says it does not guarantee a full JavaScript event loop, so browser APIs and timers such as setTimeout and setInterval are not available through the common interface. It also advises relying on ES3-level features unless you have checked the selected runtime. MiniRacer gives you V8 behavior, but that does not make either library a security sandbox.

Handling modules, JSON, and return values

Passing JSON safely

Use Ruby's JSON encoder rather than interpolating unescaped user input into JavaScript source:

require "json"
require "execjs"

payload = {name: "Ada", roles: ["admin", "author"]}
json = JSON.generate(payload)
source = "JSON.parse(#{json.dump}).roles.length"
puts ExecJS.eval(source)
# 2

For repeated calls, pass the Ruby hash directly to a compiled function:

require "execjs"

context = ExecJS.compile(<<~JS)
  function roleCount(user) {
    return user.roles.length;
  }
JS

puts context.call("roleCount", {"roles" => ["admin", "author"]})

CommonJS and browser globals

ExecJS and MiniRacer execute JavaScript without a browser DOM. Code that expects window, document, cookies, layout, or network access will fail unless you provide compatible shims. Likewise, a source file using require or ES module imports may need to be bundled into a single script first; do not assume Node's module loader exists inside an arbitrary ExecJS runtime.

Errors and troubleshooting

Symptom Likely cause Fix
ExecJS::RuntimeUnavailable No supported JavaScript runtime is installed or discoverable. Install a documented runtime such as Node.js, verify ExecJS.runtime, and check the production PATH.
SyntaxError The string is invalid JavaScript, or Ruby interpolation changed it. Print the generated source, run it in the selected engine, and use a heredoc for multiline code.
ReferenceError: document is not defined The code expects browser globals. Use a DOM-capable environment, remove the browser dependency, or provide a deliberate shim.
setTimeout is not defined ExecJS does not promise an event loop. Rewrite the code synchronously or use a runtime and integration designed for asynchronous work.
Works locally, fails in CI Different runtime, engine version, or native dependency. Log the runtime name and version, pin deployment dependencies, and test the same container image.
Calls become slower over time A persistent context is retaining growing data. Clear references, limit input size, or recreate the context periodically.
Ruby process crashes or is killed Native V8 or runtime resource pressure. Set MiniRacer limits where supported, cap source and input sizes, and isolate expensive jobs.

Security boundaries

Do not treat ExecJS as a sandbox for arbitrary tenant or user supplied JavaScript. The project explicitly warns that automatically detected runtimes have different sandbox properties and advises against evaluating input you would not feel comfortable passing to Ruby's eval. Validate who can submit code, isolate sensitive workloads, impose time and memory limits, and run untrusted jobs in a separate process or service with operating-system restrictions.

Performance and reliability guidance

  • Compile once: Reuse a context for a stable library instead of compiling identical source for every request.
  • Keep contexts scoped: A context is stateful. Reusing one across unrelated tenants can leak variables or create cross-request coupling.
  • Bound work: Limit source length, input size, recursion, and execution time. MiniRacer's documented timeout and memory controls are useful when you select that engine.
  • Pin the runtime: Feature differences are a major source of “works on my machine” failures. Record the engine and version in build output.
  • Measure conversion: Large Ruby hashes and arrays must cross the Ruby/JavaScript boundary. For bulk data, compare JSON serialization with direct argument conversion.
  • Plan for startup: Native gems and external runtimes add deployment work. Build and smoke-test the exact production image.

Or skip the browser setup

If your actual goal is to obtain a clean screenshot of a page after JavaScript runs, you can avoid managing a browser runtime yourself with ScreenshotNeo. It accepts one GET request and returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation for all options.

ScreenshotNeo cleans common overlays before returning the captured page.
ScreenshotNeo cleans common overlays before returning the captured page.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', image));

Cookie and consent banners are accepted before capture, and more than 60 known consent platforms, newsletter popups, and chat widgets can be removed. You can turn each cleanup step off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and whether it was billed. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

Available capture controls include full-page screenshots with lazy images loaded, CSS element capture, dark mode, 12 device presets or custom viewports, retina scale, PDF paper settings and page ranges, custom CSS and JavaScript, pre-capture clicks, hidden selectors, selector or delay or network-idle waits, request and resource blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Existing parameter names used by other screenshot APIs also work, which helps when migrating.

The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account.

Short FAQ

Can Ruby's eval load JavaScript?

No. It parses Ruby. Use ExecJS or MiniRacer to invoke a JavaScript engine.

Which option should a Rails app use?

Start with ExecJS when runtime portability matters. Choose MiniRacer when you explicitly need embedded V8 and its documented controls.

Can I run browser JavaScript with these gems?

Not by themselves. DOM, layout, cookies, and browser APIs require a browser or a compatible environment.

Should I reuse one context forever?

Reuse is efficient for stable code, but contexts retain state. Scope them carefully and recreate them when memory or isolation requires it.

How do I make runtime behavior reproducible?

Pin the gem, runtime, engine version, and deployment image, then log the selected runtime during startup.