Skip to content

Instantly share code, notes, and snippets.

@adamelliotfields
Last active August 11, 2023 16:17
Show Gist options
  • Save adamelliotfields/e0e503e1ba17ab13a3b1e2b7c263cb0e to your computer and use it in GitHub Desktop.
Save adamelliotfields/e0e503e1ba17ab13a3b1e2b7c263cb0e to your computer and use it in GitHub Desktop.
Grafana Dashboard Screenshot using Puppeteer
#!/usr/bin/env node
/**
* Grafana Dashboard Screenshot
*
* Derived from https://github.com/sindresorhus/capture-website/blob/v0.8.0/index.js
* by @sindresorhus (MIT).
*/
const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');
const util = require('util');
const writeFileAsync = util.promisify(fs.writeFile);
// Kiosk mode means our dashboard takes up the full viewport.
const url = 'http://localhost:3000/d/mxDGB6xZz/kubernetes?orgId=1&kiosk';
const selector = '.react-grid-layout';
const file = 'screenshot.png';
const pageOptions = {
timeout: 60000,
waitUntil: 'networkidle2',
};
const selectorOptions = {
timeout: 60000,
visible: true,
};
const viewportOptions = {
width: 1200,
deviceScaleFactor: 2,
};
const screenshotOptions = {
fullPage: false,
};
const fileOptions = {
flag: 'w',
};
const getHeight = element => {
const { height } = element.getBoundingClientRect();
return height;
};
const getClip = (element) => {
const { height, width, x, y } = element.getBoundingClientRect();
return { height, width, x, y };
};
// TODO: Add debug messages and error handling.
puppeteer.launch().then(async (browser) => {
const page = await browser.newPage();
await page.goto(url, pageOptions);
await page.waitForSelector(selector, selectorOptions);
// Get the height.
viewportOptions.height = await page.$eval(selector, getHeight);
// Resize the viewport and reload the page so all panels load.
await page.setViewport(viewportOptions);
await page.reload(pageOptions);
await page.waitForSelector(selector, selectorOptions);
// Get the clipping region.
screenshotOptions.clip = await page.$eval(selector, getClip);
const buffer = await page.screenshot(screenshotOptions);
await page.close();
await browser.close();
await writeFileAsync(path.join(__dirname, file), buffer, fileOptions);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment