Headless Browser

Definition

A headless browser is a web browser that operates without a graphical user interface. It functions invisibly and can be controlled programmatically, making it particularly useful for automating web page interactions, rendering web pages to images or PDFs, and performing tasks like rendering visualizations and reports under Node.js.

Overview

Headless browsers are primarily used for automating and testing websites. They allow developers to run automated tests without needing to see or interact with the web page directly, which is especially beneficial in continuous integration and deployment environments. These browsers can simulate web pages, execute JavaScript, and capture browser-based visualizations, outputting them as PNG or PDF files. This capability is useful for tasks such as web scraping, capturing screenshots for documentation and marketing, prerendering visualizations for websites, and wrapping legacy web pages as APIs.

Usage Examples

Capturing Visualizations

Headless browsers can be used to capture visualizations to static image files. For instance, using a headless browser under Node.js, developers can capture a visualization and save it as an image file. This process is illustrated in Figure 11.2.

Figure 11.2 We can use a headless browser under Node.js to capture our visualization to a static image file. Figure 11.2 We can use a headless browser under Node.js to capture our visualization to a static image file.

Automating Web Page Interactions

The following code snippet demonstrates how to use Nightmare, a headless browser, to capture a chart to an image file:

Listing 11.4 Capturing the chart to an image file using Nightmare (listing-11.4/index.js)

const webServer = require('./web-server.js');
const Nightmare = require('nightmare');

webServer.start()    #1  
    .then(server => {
        const outputImagePath = "./output/nyc-temperatures.png";

 const nightmare = new Nightmare();    #2  
 return nightmare.goto("http://localhost:3000")    #3  
 .wait("svg")    #4  
 .screenshot(outputImagePath)    #5  
 .end()    #6  
 .then(() => server.close());    #7  
    })
    .then(() => {
        console.log("All done :)");
    })
    .catch(err => {
        console.error("Something went wrong :(");
        console.error(err);
    })

#1   Starts the web server
#2   Creates the Nightmare instance
#3   Points the browser at the web server we started
#4   Waits until an svg element appears onscreen, indicating that the chart has loaded
#5   Captures a screenshot to an image file
#6   Ends the Nightmare session. Any queued operations are completed, and the headless browser is terminated.
#7   Stops the web server when we’re done

Capturing Specific Web Page Elements

To capture specific parts of a web page, such as a chart, the screenshot function can be modified to pass in a rectangle that defines the part of the web page to capture. This is demonstrated in Listing 11.6.

Listing 11.6 Capturing the entire chart (listing-11.6/toolkit/capture-web-page.js)

function captureWebPage (urlToCapture, captureElementSelector, outputImagePath) {

    const nightmare = new Nightmare();
    return nightmare.goto(urlToCapture)
        .wait(captureElementSelector)
 .evaluate(captureElementSelector => {    #1  
 const body = document.querySelector("body");    #2  
 const captureElement =    #3  
 document.querySelector(captureElementSelector);    #3  
 const captureRect =    #4  
 captureElement.getBoundingClientRect();    #4  
 return {    #5  
 documentArea: {    #6  
                    width: body.scrollWidth,
                    height: body.scrollHeight
                },
 captureArea: {    #7  
                    x: captureRect.left,
                    y: captureRect.top,
                    width: captureRect.right - captureRect.left,
                    height: captureRect.bottom - captureRect.top
                }
            };
        }, captureElementSelector)
 .then(pageDetails => {    #8  
 return nightmare.viewport(    #9  
 pageDetails.documentArea.width,    #9  
 pageDetails.documentArea.height    #9  
 )    #9  
 .screenshot(outputImagePath, pageDetails.captureArea)    #10  
                .end();
        });
};

#1   Evaluates JavaScript code within the headless browser
#2   Finds the body element of the web page
#3   Finds the HTML element to be captured in the DOM
#4   Gets the area that we want to capture
#5   Returns details computed in the headless browser to Node.js
#6   Returns the scrollable area of the page. We’ll expand the size of the browser window to cover the entire document (removing any scrollbars we might otherwise capture).
#7   Returns the rect of the area of the page (e.g., the chart) that we want to capture
#8   Retrieves details computed in the headless browser. We can now use these values in subsequent Node.js code.
#9   Sets the viewport to cover the area of the chart
#10   Captures a screenshot to an image file

Rendering Web Pages to PDF

Headless browsers can also render web pages to PDF files. Listing 11.8c shows how to capture a multipage report to a PDF file.

Listing 11.8c Rendering a multipage report to a PDF file (extract from listing-11.8/index.js)

function captureReport (urlToCapture,
 captureElementSelector, outputPdfFilePath) {    #1  

    const nightmare = new Nightmare();
    return nightmare.goto(urlToCapture)
        .wait(captureElementSelector)
        .evaluate(() => {
 const body = document.querySelector("body");    #2  
 return {    #3  
 documentArea: {    #4  
                    width: body.scrollWidth,
                    height: body.scrollHeight
                },
            };
        })
 .then(pageDetails => {    #5  
            const printOptions = {
 marginsType: 0,    #6  
 pageSize: {    #7  
 width: 297000,    #8  
 height: 210000,    #9  
                },
                landscape: true,
            };
 return nightmare.viewport(    #10  
 pageDetails.documentArea.width,    #10  
 pageDetails.documentArea.height    #10  
 )    #10  
 .pdf(outputPdfFilePath, printOptions)    #11  
                .end();
        });
};

#1   This is a toolkit function that captures a multipage report to a PDF file.
#2   Finds the body element of the web page
#3   Returns details computed in the headless browser to Node.js
#4   Returns the scrollable area of the page. We’ll expand the size of the browser window to cover the entire documents (removing any scrollbars we might otherwise capture).
#5   Retrieves details computed in the headless browser. We can now use these values in subsequent Node.js code.
#6   Specifies no margins. This allows us to explicitly set our margins via CSS.
#7   Lists the size of each page. These values match the specification for the A4 page size standard, but in landscape.
#8   Sets the width of the page, 29.7 cm (in microns. Don't ask me why they put this is in microns.)
#9   Sets the height of the page, 21 cm (in microns)
#10   Sets the viewport to cover the area of the chart
#11   Captures the entire web page to a PDF report

Debugging

Debugging code in a headless browser can be achieved by displaying the browser's window and enabling devtools. This allows developers to see what is being rendered and troubleshoot issues using the browser's console and devtools. Listing 11.9 demonstrates how to create a Nightmare instance for debugging purposes.

Listing 11.9 Creating the Nightmare instance for debugging

const nightmare = Nightmare({
 show: true,    #1  
 openDevTools: { mode: "detach" }    #2  
});

#1   Shows the headless browser window. Ultimately, we don’t want this, but it’s useful to see what’s going on when we’re debugging.
#2   Opens the devtools for the web page so we can troubleshoot if necessary

Tools

Nightmare is a tool that allows developers to control Electron running as a headless browser, as shown in Figure 11.3.

Figure 11.3 Nightmare allows us to control Electron running as a headless browser. Figure 11.3 Nightmare allows us to control Electron running as a headless browser.

FAQ (Frequently asked questions)

What is Nightmare in the context of headless browsers?