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 evaluate JavaScript source stored in a Java String, use a JavaScript engine and call eval(). To load and render a website that depends on JavaScript, use a page environment such as HtmlUnit—or drive a real browser with Selenium when browser fidelity matters. An engine that evaluates code is not, by itself, a browser: it does not automatically provide the page’s window, document, DOM, network activity, or browser state.

Choose the right kind of JavaScript execution

The phrase “load JavaScript from a String for website rendering” can mean two different tasks. First, your Java program may need to evaluate a short snippet, such as a calculation or a transformation, without any webpage. Second, it may need to load a website, let its scripts run against the page, and inspect the result. The first task is a JavaScript-runtime problem; the second is a browser-environment problem.

What you need Use What it gives you
Evaluate a source string without browser APIs javax.script with an installed JavaScript engine A way to pass source to an engine using eval(); it does not provide a website DOM.
Embed a JavaScript runtime in a Java application GraalJS An embeddable JavaScript runtime with Java interoperability, according to its project documentation.
Load a page and run its scripts in a Java browser-like client HtmlUnit Page retrieval, JavaScript execution, cookies, browser state, and page objects.
Match behavior of real browser engines Selenium Automation through a real browser rather than a browser-like Java client.
Parse static HTML without running scripts Jsoup HTML parsing without the extra browser behavior when that is all the task needs.

This distinction determines whether JavaScript can access browser globals. If the code refers to window, document, clicks, cookies, or content inserted after a network response, execute it in a page context. If it only transforms data, an embedded runtime may be simpler.

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

Evaluate a JavaScript string with javax.script

The Java Scripting API provides the basic manager → engine → evaluation workflow. Oracle’s Java Scripting Programmer’s Guide (Java SE 12) demonstrates obtaining a ScriptEngine by name and calling eval(). Its example uses the name nashorn; treat that engine name as guide-specific, not as a guarantee that every JDK installation includes that engine. The same guide notes that engine lookup returns null when the requested engine is unavailable.

Minimal example

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class EvaluateJavaScript {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        if (engine == null) {
            throw new IllegalStateException(
                "No JavaScript engine named nashorn is available"
            );
        }

        Object result = engine.eval("1 + 2");
        System.out.println(result);
    }
}

The expected result, when a compatible engine is available, is 3. The example’s purpose is to show the API pattern; the availability of the particular engine is a separate runtime and dependency question. A missing engine is not a syntax error in your JavaScript, and adding javax.script imports alone does not install an engine implementation.

Use an engine appropriate to your project

For a current embeddable JavaScript runtime, GraalJS documents Java embedding, Java interoperability, and Maven artifacts in the org.graalvm.polyglot family. Choose and configure the dependency using the current GraalJS project documentation for the JDK and release you use; the Java SE 12 Nashorn example does not establish a current GraalJS version or dependency declaration. After configuring an engine, use that engine’s supported embedding API and verify its availability at startup rather than assuming that every Java installation has the same JavaScript provider.

GraalJS also documents a compatibility-mode load(source) function that evaluates source, including forms represented with a name and script. This is useful when a program specifically needs that runtime compatibility behavior. It does not turn GraalJS into a browser: load() does not, by itself, create a DOM or supply window and document.

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.

Run a string inside a loaded page with HtmlUnit

HtmlUnit’s WebClient models a browser-like client within Java. It can retrieve a page, execute JavaScript, retain cookies and browser state, and expose page objects. For a string that needs the page’s globals, load the page first and use HtmlPage.executeJavaScript(String). It returns a ScriptResult, which includes the JavaScript result object.

Page-context example

import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class RunScriptInPage {
    public static void main(String[] args) throws Exception {
        try (WebClient client = new WebClient()) {
            // HtmlUnit documents JavaScript as enabled by default.
            HtmlPage page = client.getPage("https://example.com");

            ScriptResult result = page.executeJavaScript(
                "document.title"
            );

            System.out.println(result.getJavaScriptResult());
        }
    }
}

Use the HtmlUnit version and package API selected for your application; the example shows the documented page-execution pattern, not a version-pinned build file. Replace the URL with the page you are permitted to access. The returned value is the evaluation result in that page context, not a screenshot. If the goal is to interact with a control or trigger event handlers, use the page’s element actions where possible instead of directly calling the script engine; HtmlUnit’s documentation cautions that direct engine use is generally not the preferred interaction route.

Asynchronous pages and script failures

Modern pages may start requests or timers and update the DOM later. A page workflow can appear complete before an AJAX response arrives, so an immediate inspection can see an intermediate state. Use HtmlUnit’s documented mechanisms for asynchronous JavaScript and background work, and wait for the specific page condition your task needs rather than assuming the first load means every update has finished.

HtmlUnit documents JavaScript as enabled by default. Its tutorial also calls out a practical difference from real browsers: by default, an unhandled JavaScript error stops JavaScript execution. If a target page has unrelated script errors, inspect the exception and HtmlUnit’s JavaScript error-handling configuration before concluding that the page has no usable content. Disabling or relaxing error handling may let more scripts run, but it can also conceal a genuine failure in the behavior you are trying to test.

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

When HtmlUnit is not the right rendering choice

Use Jsoup for static markup

If the required data is already present in the server-delivered HTML and you do not need scripts, cookies, browser state, or user interactions, parsing with Jsoup avoids simulating browser behavior. It is not a substitute when JavaScript creates the content you need.

Use Selenium for real-browser behavior

HtmlUnit is browser-like, not a promise of identical output across real browser engines. If correctness depends on browser-specific APIs, rendering behavior, or compatibility with an actual browser, HtmlUnit’s getting-started guide points to Selenium as the real-browser option. It adds browser automation and browser management to the job, so reserve it for cases where that additional fidelity is important.

Use GraalJS for embedded runtime needs

GraalJS is appropriate when a Java application needs an embeddable JavaScript runtime and Java interoperability, but not a webpage. Use HtmlUnit or Selenium for page behavior instead of trying to make a standalone engine provide browser objects it does not supply.

Troubleshooting common failures

Symptom Likely cause What to check
getEngineByName() returns null No registered engine matches the requested name. Check the engine name and the runtime/dependency configuration. Do not treat the Java Scripting API as proof that a JavaScript provider is installed.
ReferenceError: document is not defined The source is running in a plain JavaScript engine rather than a webpage context. Load the page and evaluate in HtmlUnit’s page context, or use a browser controlled through Selenium if real-browser behavior is required.
The script runs but sees old or missing page content The relevant DOM update depends on an asynchronous response or later page work. Wait for the expected page condition or background work using the selected page tool’s documented approach before inspecting.
JavaScript stops after an error from the site HtmlUnit’s default behavior stops execution after an unhandled JavaScript error. Inspect the error and configure error handling deliberately; distinguish unrelated site errors from failure in the script under test.
HtmlUnit’s result differs from a browser The workflow relies on behavior not modeled identically by a browser-like client. Reduce the task to needed DOM behavior where possible; use Selenium when actual browser-engine behavior is essential.
A page loads, but there is no rendered image Page loading and JavaScript evaluation return page data or objects, not necessarily a screenshot artifact. Choose a screenshot-capture service or a browser screenshot workflow if the deliverable is an image or PDF.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose using the page’s real requirements

Before adding a library, answer four questions: Does the source use window or document? Does it depend on page requests, cookies, or asynchronous updates? Must it match a real browser? Can your project add and maintain a separate JavaScript engine dependency? A standalone engine is smallest when the first two answers are no; HtmlUnit fits Java-side page loading and browser-like behavior; Selenium fits a real-browser requirement; Jsoup fits static markup.

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

For operational reliability, check engine availability during application startup, make page waits depend on the content you need, and retain the actual JavaScript or load error when diagnosing failures. Do not silently convert an unavailable engine, script exception, or unfinished asynchronous page into an apparently successful empty result. For repeatable tests, use a controlled page and distinguish the test script’s errors from errors already present on the site.

Or skip the browser setup

If your aim is a screenshot or PDF rather than Java-side DOM interaction, ScreenshotNeo is a website screenshot API and MCP server; it does not replace HtmlUnit for executing arbitrary JavaScript in your Java process. A single GET request can capture a URL as PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation.

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

ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response includes X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Learn about ScreenshotNeo or sign up for 1,000 free screenshots a month with no card.

Frequently Asked Questions

Does HtmlUnit return an image when I execute a script?

No. Page execution returns a script result and page access, not automatically a screenshot file. Use a screenshot-capture workflow when the required output is an image or PDF.

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.