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.

To evaluate JavaScript source stored in a Java String, use ScriptEngine.eval(String) with an available JavaScript engine. To load and render a website that depends on JavaScript, use a browser-like page environment such as HtmlUnit—or Selenium when you need a real browser. A standalone engine does not provide window, document, page loading, or a rendered website.

First choose what you mean by “rendering”

There are two distinct tasks that are often conflated:

  • Evaluate a script string: execute JavaScript code held in a Java String. The Java Scripting API provides the ScriptEngine interface and its eval() method, provided an engine implementation is available.
  • Load a website and run its scripts: retrieve a page, maintain browser state such as cookies, provide browser APIs, and wait for page behavior. For this, use a browser-like client or automate a real browser.

If the code references window or document, or depends on the page’s network requests, DOM, or event handlers, a standalone JavaScript engine is not enough.

Evaluate a JavaScript string in Java

The basic Java Scripting API workflow is to create a ScriptEngineManager, look up an engine, check that lookup succeeded, and pass the source string to eval(). Oracle’s Java SE 12 scripting guide demonstrates this sequence with Nashorn. Its example is historical: do not assume that a current JDK includes Nashorn or any JavaScript engine. The API lookup returns null if no engine with the requested name is available. See Oracle’s Java Scripting Programmer’s Guide.

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.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class EvaluateJavaScript {
    public static void main(String[] args) throws ScriptException {
        String source = "var total = 19 + 23; total";

        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(source);
        System.out.println(result);
    }
}

The expected printed value for this expression is the engine’s representation of 42. A different engine may return a different Java object type for JavaScript values. Handle script errors through ScriptException, as shown in the method signature.

What this does—and does not—provide

This evaluates code in an engine context; it does not fetch a URL, construct a browser DOM, or render pixels. Even a successfully evaluated script that refers to document can fail because those browser globals are not supplied by this example.

When a JavaScript engine is needed today

If you need an embeddable JavaScript runtime in a Java application, GraalJS documents Java embedding and interoperability, along with Maven artifacts in the org.graalvm.polyglot group. Follow its current setup documentation for the compatible artifacts and version for your project: GraalJS documentation. The exact dependency and runtime setup are version-sensitive, so do not copy a Nashorn lookup name and assume it will resolve to GraalJS.

Run JavaScript in a loaded page with HtmlUnit

HtmlUnit’s WebClient provides a browser-like programming model within Java: it retrieves pages, executes JavaScript, and keeps browser state such as cookies. It is useful for JavaScript-aware testing, automation, and scraping without opening a graphical browser. Its starting guide also recommends Jsoup when you only need to parse static HTML, and Selenium when the work requires real-browser behavior. See HtmlUnit’s getting-started guide.

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

For a page you already loaded, call HtmlPage.executeJavaScript(String) to run a source string in that page’s context and obtain a ScriptResult. In normal user flows, prefer page actions such as clicking an element when possible; executing arbitrary JavaScript directly is not always equivalent to interacting with a browser as a user would. The HtmlUnit JavaScript documentation also notes that JavaScript support is enabled by default. See HtmlUnit’s JavaScript tutorial and the HtmlPage API.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

The following illustrates the shape of the workflow. Use the HtmlUnit artifact and API compatible with your project’s selected version; consult its current getting-started guide for dependency coordinates and any version-specific API changes.

import org.htmlunit.WebClient;
import org.htmlunit.html.HtmlPage;
import org.htmlunit.javascript.ScriptResult;

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

            ScriptResult result = page.executeJavaScript(
                "document.title"
            );
            System.out.println(result.getJavaScriptResult());
        }
    }
}

The example executes a short expression against the page’s document and prints its result. Replace the example URL with a page you are authorized to access. If a site’s script relies on features HtmlUnit does not model as the target browser does, use Selenium with the browser engine your application needs to match.

Asynchronous page work and JavaScript errors

A page can finish its initial load before its asynchronous requests have completed. HtmlUnit’s tutorial warns that an AJAX response may arrive after a page workflow appears complete. If the value you need is populated asynchronously, wait for the relevant page condition or request to complete rather than reading immediately after navigation; choose a wait strategy appropriate to your application and HtmlUnit version.

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

Another important difference from real browsers is error handling: HtmlUnit’s default configuration stops JavaScript execution after an unhandled JavaScript error. If later page behavior is missing, inspect script errors first. The tutorial documents how to configure JavaScript error handling and how to enable or disable JavaScript for a WebClient. Avoid turning off error visibility merely to make a test pass; determine whether the error reflects an unsupported feature, a site defect, or an incorrect test setup.

Choose the right Java approach

Need Starting point Reason
Evaluate a small script string without browser objects javax.script plus an installed engine The manager-to-engine-to-eval() workflow is direct, but engine availability must be checked. Oracle guide.
Embed a JavaScript runtime in a Java application GraalJS Its documentation covers Java embedding and interoperability. GraalJS docs.
Load a page and execute scripts in a Java browser-like client HtmlUnit WebClient handles page retrieval, JavaScript, cookies, and browser state. HtmlUnit guide.
Automate behavior that must match real browser engines Selenium HtmlUnit’s guide identifies Selenium as the real-browser option. HtmlUnit guide.
Parse static HTML without running JavaScript Jsoup Use a parser rather than a browser-like runtime when browser behavior is unnecessary. HtmlUnit guide.

Decide based on four questions: does the code need browser globals; must the page make network requests and preserve state; how closely must behavior match a real browser; and can your application manage a separate JavaScript runtime dependency?

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

GraalJS load(source) is not website rendering

GraalJS’s compatibility documentation describes a load(source) function for evaluating source, including source forms represented by an object with name and script. Its scripting compatibility mode also discusses string inputs. This is a runtime scripting feature, not a browser page loader: it does not by itself create a website DOM or render a page. For those requirements, pair the runtime with a page/browser environment instead. See GraalJS documentation and its JavaScript compatibility documentation.

Or skip the browser setup

If your goal is an image or PDF of a page rather than Java-side interaction with its DOM, a screenshot API can avoid setting up and maintaining browser automation. ScreenshotNeo is a website screenshot API and MCP server; its endpoint accepts one GET request with a URL and returns a PNG, JPEG, WebP, or PDF. It is not a replacement for HtmlUnit or Selenium when your Java program must inspect or manipulate page state.

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

Example cURL request (see the ScreenshotNeo API documentation):

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

The same endpoint can be called from Java using an HTTP client; the request needs your access key and the target URL. ScreenshotNeo removes cookie/consent banners, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response includes X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to try 1,000 screenshots a month with no card.

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

Troubleshooting JavaScript execution and page loading

getEngineByName() returns null

Cause: No engine registered under that name is available to the application. Having javax.script classes does not guarantee a JavaScript engine is installed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Fix: Check the engine lookup before calling eval(). Add and configure a supported engine such as GraalJS using its current documentation, then use the engine’s documented integration rather than assuming the Nashorn name will work.

The script reports that window or document is undefined

Cause: The code is running in a standalone JavaScript runtime, not in a browser page.

Fix: Load the target page in HtmlUnit and run code in its page context, or automate a real browser with Selenium if real-browser behavior is required.

The page loads but expected content is absent

Cause: Content may arrive through asynchronous requests, or a script error may have halted execution. HtmlUnit’s default behavior stops JavaScript after an unhandled script error.

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

Fix: Check the JavaScript error output, allow the relevant asynchronous work to finish, and verify that the page feature is supported by your chosen environment. For site behavior that depends on a real browser engine, use Selenium.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Direct JavaScript execution does not trigger the expected interaction

Cause: Calling a script directly may not reproduce the same event path or state changes as a user action.

Fix: Use HtmlUnit page actions, such as clicking the relevant element, when the purpose is to exercise the page’s interaction. Use direct executeJavaScript() for deliberate in-page evaluation.

The script runs but no rendered image is produced

Cause: ScriptEngine.eval() evaluates code; it does not capture rendered pixels.

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

Fix: Use a browser automation and screenshot workflow if your Java application needs local browser control, or use a screenshot API when the required output is simply a page image or PDF.

Frequently Asked Questions

Can I use ScriptEngine.eval() to render a webpage?

No. It evaluates JavaScript source in an engine context; it does not load a page or provide a DOM and browser rendering.

Does every Java installation include Nashorn?

No. Oracle’s Java SE 12 guide uses Nashorn as an example and documents that a missing named engine returns null. Check engine availability and use current runtime documentation.

When should I use Jsoup instead of HtmlUnit?

Use Jsoup when you need to parse static HTML and do not need JavaScript execution or browser behavior.

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.