JavaScript rendering | rust-crawler | Spatie       

 SPATIE  

rust-crawler
============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Advanced-usage  JavaScript rendering

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/rust-crawler/v1) 

  JavaScript rendering    
- [ Introduction ](https://spatie.be/docs/rust-crawler/v1/introduction)
- [ Installation &amp; setup ](https://spatie.be/docs/rust-crawler/v1/installation-setup)
- [ Support us ](https://spatie.be/docs/rust-crawler/v1/support-us)
- [ Questions and issues ](https://spatie.be/docs/rust-crawler/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/rust-crawler/v1/changelog)
- [ About us ](https://spatie.be/docs/rust-crawler/v1/about-us)

Basic usage
-----------

- [ Your first crawl ](https://spatie.be/docs/rust-crawler/v1/basic-usage/starting-your-first-crawl)
- [ Crawl responses ](https://spatie.be/docs/rust-crawler/v1/basic-usage/handling-crawl-responses)
- [ Using observers ](https://spatie.be/docs/rust-crawler/v1/basic-usage/using-observers)
- [ Collecting URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/collecting-urls)
- [ Filtering URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/filtering-urls)
- [ Testing ](https://spatie.be/docs/rust-crawler/v1/basic-usage/testing)
- [ Tracking progress ](https://spatie.be/docs/rust-crawler/v1/basic-usage/tracking-progress)

Configuring the crawler
-----------------------

- [ Concurrency &amp; throttling ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/crawl-behavior)
- [ Limits ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/setting-crawl-limits)
- [ Extracting resources ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/extracting-resources)
- [ Configuring requests ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/configuring-requests)
- [ Response filtering ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/handling-responses)
- [ Respecting robots.txt ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/respecting-robots-txt)

Advanced usage
--------------

- [ JavaScript rendering ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/rendering-javascript)
- [ Custom link extraction ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/extracting-custom-links)
- [ Custom request handlers ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/custom-request-handlers)
- [ Crawling across requests ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/crawling-across-requests)
- [ Custom crawl queue ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/using-a-custom-crawl-queue)
- [ Graceful shutdown ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/graceful-shutdown)

 JavaScript rendering
====================

###  On this page 

1. [ Configuring Chrome or Chromium ](#content-configuring-chrome-or-chromium)
2. [ Choosing when to render ](#content-choosing-when-to-render)
3. [ Using Cloudflare Browser Rendering ](#content-using-cloudflare-browser-rendering)
4. [ Custom renderers ](#content-custom-renderers)
5. [ Disabling JavaScript execution ](#content-disabling-javascript-execution)
6. [ Browser safety ](#content-browser-safety)

By default, the crawler will not execute JavaScript. You can enable JavaScript rendering by passing a renderer to `renderer()`.

Configuring Chrome or Chromium
--------------------------------------------------------------------------------------------------------------------------------------------------

`NativeBrowserRenderer` requires Chrome or Chromium to be installed. No PHP or Node runtime is needed. Only use it in a trusted or network-isolated environment; read [browser safety](#browser-safety) before enabling it.

```
use spatie_crawler::{Crawler, NativeBrowserRenderer, RenderMode, RenderOptions};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result {
    let renderer = NativeBrowserRenderer::trusted_network(2)?
        .options(RenderOptions {
            wait_for_selector: Some("main a".into()),
            wait_for_expression: Some("window.appReady === true".into()),
            wait_after_load: Duration::from_millis(100),
            ..RenderOptions::default()
        });

    let mut crawl = Crawler::builder("https://example.com")?
        .renderer(renderer)
        .render_mode(RenderMode::Always)
        .max_pages(20)
        .build()?
        .crawl();

    while let Some(event) = crawl.next().await {
        println!("{event:?}");
    }
    Ok(())
}
```

Set `CHROME_PATH` or call `.executable("/path/to/chromium")` to select an executable. Otherwise the renderer searches common Chromium names on `PATH`. The positive argument to `trusted_network` limits concurrent browser contexts, separately from crawler concurrency. One browser process is reused, with a fresh incognito context per render; cookies and local storage do not carry between pages.

Rendering waits for `DOMContentLoaded`, then the selector, expression and post-load delay in that order. `initialization_script` runs before page scripts. `javascript` runs after the waits and before HTML capture. Only use trusted application code for these script options.

Choosing when to render
-----------------------------------------------------------------------------------------------------------------------------

- `RenderMode::Always` invokes the renderer for responses with an empty content type or a `text/html` content type. This is the default mode when a renderer is registered.
- `RenderMode::Auto` uses a script/shell heuristic or HTTP challenge status to decide whether to render. It will miss some JavaScript-dependent pages.

Rendering gets a separate `request_timeout` deadline after fetching. The crawler checks the returned body size and URL policy before extraction. Rendering preserves the original HTTP status and transfer statistics; it does not turn an HTTP error into a success.

Using Cloudflare Browser Rendering
--------------------------------------------------------------------------------------------------------------------------------------------------------------

The `CloudflareRenderer` uses a Cloudflare Browser Rendering `/content` endpoint or compatible gateway to render JavaScript. Pass the full endpoint URL and load the token from your application's secrets:

```
use spatie_crawler::{CloudflareRenderer, Crawler, RenderMode};

#[tokio::main]
async fn main() -> Result {
    let token = std::env::var("CLOUDFLARE_API_TOKEN")?;
    let endpoint = std::env::var("CLOUDFLARE_CONTENT_ENDPOINT")?.parse()?;
    let renderer = CloudflareRenderer::new(endpoint, token)?;
    let mut crawl = Crawler::builder("https://example.com")?
        .renderer(renderer)
        .render_mode(RenderMode::Always)
        .max_pages(20)
        .build()?
        .crawl();

    while let Some(event) = crawl.next().await {
        println!("{event:?}");
    }
    Ok(())
}
```

The request contains `url`, `setExtraHTTPHeaders` and `gotoOptions.timeout`. The adapter accepts HTML in `content`, a string `result` or `result.content`, and checks a returned final URL when present. Endpoint redirects are refused. The rendering service must provide its own network isolation; see [browser safety](#browser-safety).

Custom renderers
--------------------------------------------------------------------------------------------------------

You can create your own JavaScript renderer by implementing `Renderer`. Add `async-trait = "0.1"` to your dependencies. This example accepts an application-supplied async function that returns rendered HTML:

```
use async_trait::async_trait;
use spatie_crawler::{Crawler, FetchRequest, FetchResponse, Renderer};
use std::future::Future;

struct ApplicationRenderer(F);

#[async_trait]
impl Renderer for ApplicationRenderer
where
    F: Fn(FetchRequest) -> Fut + Send + Sync,
    Fut: Future + Send,
{
    async fn render(
        &self,
        request: FetchRequest,
        mut response: FetchResponse,
    ) -> spatie_crawler::Result {
        let html = (self.0)(request).await?;
        response.body = html.into();
        response.headers.remove("content-length");
        response.headers.remove("content-encoding");
        response.headers.remove("content-type");
        response.header("content-type", "text/html; charset=utf-8")
    }
}

fn crawler_with_renderer(render_html: F) -> spatie_crawler::Result
where
    F: Fn(FetchRequest) -> Fut + Send + Sync + 'static,
    Fut: Future + Send,
{
    Crawler::builder("https://example.com")?
        .renderer(ApplicationRenderer(render_html))
        .build()
}
```

A custom renderer manages its browser or service lifecycle. Honor the request's timeout, size limit, headers and redirect policy, and update `final_url` and redirect history when navigation changes. Async deadlines cannot preempt blocking code.

Disabling JavaScript execution
--------------------------------------------------------------------------------------------------------------------------------------------------

If you've registered a renderer but want to disable it, set `.render_mode(RenderMode::Never)` on the builder. Without a registered renderer, no mode executes JavaScript.

Browser safety
--------------------------------------------------------------------------------------------------

The HTTP fetcher's [network safeguards](../configuring-the-crawler/configuring-requests#network-safety) do not protect browser requests. Scripts, frames, workers, WebSockets and subresources can reach the browser's host network. Main-page URL checks are not an SSRF firewall. Use OS/container network isolation before rendering untrusted sites, whether locally or through a remote service.

Keep Chromium's OS sandbox enabled. Use `.chromium_sandbox(false)` only inside an already isolated environment whose kernel cannot provide that sandbox, not as a general installation fix.

The HTML size limit bounds captured HTML, not browser RAM or subresource downloads. Custom renderers must bound their own allocations. The native renderer forwards request headers only to the original request's origin; a remote rendering service owns its credential and subresource policies.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
