Examples

How to convert HTML to a base64 image with Selenium and JavaScript

Install Selenium for JavaScript

npm install selenium-webdriver

selenium-webdriver includes Selenium Manager, which downloads the right chromedriver automatically. The examples use ES modules — run them with node file.mjs, or set "type": "module" in your package.json.

Get the base64 encoded image of some HTML and print to screen

import { Builder } from 'selenium-webdriver';
import chrome from 'selenium-webdriver/chrome.js';

const options = new chrome.Options().addArguments('--headless=new');
const driver = await new Builder().forBrowser('chrome').setChromeOptions(options).build();

const html = '<html><body><h1>Hello World</h1></body></html>';
await driver.get('data:text/html;charset=utf-8,' + html);

// takeScreenshot already returns the image as a base64 string.
console.log(await driver.takeScreenshot());

await driver.quit();

Find out how to generate a PNG from HTML with JavaScript and Selenium.

That was 13 lines of code — plus a browser to run in production

Keeping headless browsers fed, patched and scaled is a job in itself. We built Urlbox so the same screenshot is one API call:

curl "https://api.urlbox.com/v1/YOUR_API_KEY/png?url=https://example.com"

Try the Urlbox screenshot API — free trial, no browser babysitting.