ScreenshotNeo

BlogGuides

GrabzIt API Screenshot Guide for JavaScript

Capture a URL, HTML string, or the current page with GrabzIt’s JavaScript API. Configure output, handle completion, and save captures safely.

By the ScreenshotNeo team4 October 202611 min read

Use GrabzIt’s JavaScript library to capture a remote URL, supplied HTML, or the current page with ConvertURL, ConvertHTML, or ConvertPage. Pass optional settings as an object, then choose how the result is handled with Create(), AddTo(), CreateInvisible(), or DataURI(). For browser use, authorize the page’s domain for the application key first. [GrabzIt JavaScript API]

1. Set up the JavaScript API

  1. Create a GrabzIt application key.
  2. Authorize the domain where the code will run in your GrabzIt account. Domain authorization is required for the browser JavaScript API to work and helps prevent other sites from using the key.
  3. Include the JavaScript library in the page. GrabzIt’s documentation shows a CDN-hosted library; check its current example for the current package URL and version before deploying.
  4. Call the method that matches your source and select a result handler.

The application key appears in client-side JavaScript, so domain authorization matters. Do not put an application secret or storage credentials in browser code. For storage export from browser JavaScript, use GrabzIt’s Secure Export URL option. [Authorized domains and secure captures, Secure export URLs]

2. Complete runnable example: capture a URL

Replace YOUR_APPLICATION_KEY with your key and run this page from an authorized domain. It requests a PNG at the specified output size, waits up to 25 seconds for a visible element matching #main-content, and provides callbacks for progress and errors.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>GrabzIt capture example</title>
</head>
<body>
  <div id="capture-result"></div>
  <p id="capture-status" role="status">Preparing capture…</p>

  <script src="https://cdn.jsdelivr.net/npm/@grabzit/js@/grabzit.min.js"></script>
  <script>
    const options = {
      format: "png",
      bwidth: 1366,
      bheight: 900,
      width: 1200,
      waitfor: "#main-content",
      onstart: function (id) {
        document.getElementById("capture-status").textContent =
          "Capture started: " + id;
      },
      onfinish: function (id) {
        document.getElementById("capture-status").textContent =
          "Capture ready: " + id;
      },
      onerror: function (message, code) {
        document.getElementById("capture-status").textContent =
          "Capture failed (" + code + "): " + message;
      }
    };

    GrabzIt("YOUR_APPLICATION_KEY")
      .ConvertURL("https://example.com", options)
      .AddTo("capture-result");
  </script>
</body>
</html>

The unversioned CDN URL above follows the current official documentation example format; use the CDN URL and version shown in the live [GrabzIt JavaScript guide] when publishing or pinning a dependency. The onfinish callback indicates that the capture is ready and receives its capture ID. It does not itself persist a file on your server. [JavaScript capture events]

3. Choose the right source and result method

Capture a URL

Use ConvertURL(url, options) when the page is already hosted and can be fetched by the capture service. It is usually the right choice for public pages or pages that are otherwise accessible to the service.

GrabzIt("YOUR_APPLICATION_KEY")
  .ConvertURL("https://example.com", { format: "png" })
  .Create();

Convert supplied HTML

Use ConvertHTML(html, options) when your application already has markup to render. Keep in mind that relative CSS, image, or script paths need a base address; the API’s address option supplies the URL used to resolve relative resources. Resources that are not publicly accessible may not load in the capture environment.

const markup = "<!doctype html><html><body><h1>Monthly report</h1><p>Ready to export.</p></body></html>";

GrabzIt("YOUR_APPLICATION_KEY")
  .ConvertHTML(markup, {
    address: "https://example.com/reports/",
    format: "png",
    onerror: function (message, code) {
      console.error("GrabzIt error", code, message);
    }
  })
  .Create();

Capture the visitor’s current page

Use ConvertPage(options) to capture the page in which the library is running, including its current client-side state. Page resources such as stylesheets and images must be reachable to the conversion service to appear correctly.

GrabzIt("YOUR_APPLICATION_KEY")
  .ConvertPage({ format: "png", onerror: function (message, code) {
    console.error("GrabzIt error", code, message);
  }})
  .Create();

Pick how the result is exposed

Method Use it when
Create() Insert the capture at the start of the body (or document root when there is no body).
AddTo(elementOrId) Insert it into a specific element, as in the complete example.
CreateInvisible() Create the capture without displaying it in the page.
DataURI(callback, decrypt) Receive a base64 data URL in a callback for client-side processing. Set the optional decrypt argument when the capture is encrypted.

These are result handling methods; they do not change the source being captured. A data URL keeps the encoded image in browser memory and can become large for high-resolution captures.

4. Configure format, dimensions, and rendering time

All capture parameters are optional JSON properties. Defaults, supported formats, and limits vary by output type and account package. Consult the [live JavaScript parameter reference] for the setting and output you intend to use.

Setting What it controls Practical note
format Output type, including JPG, PNG, PDF, and other documented formats. JPG and WEBP use lossy quality settings; PNG is lossless and supports transparency when enabled.
bwidth, bheight Browser viewport used to render the page. Documented default is 1366 by 1170 pixels; maximum browser dimensions are 10,000 pixels. bwidth: -1 means match document width; bheight: -1 requests full page height where supported.
width, height Output dimensions, distinct from browser viewport dimensions. Output maxima depend on package and format. When one dimension is set, the other can be scaled proportionally; -1 has special full-dimension behavior documented for relevant output types.
delay Fixed wait, in milliseconds, before capture. Default 0; maximum 30,000 ms. Use only when a known animation or delayed render needs time.
waitfor CSS selector that must match a visible element before capture. The documented maximum wait is 25 seconds. Prefer a meaningful readiness selector over a long fixed delay.
quality Compression level for applicable formats. The parameter reference documents a default compression of 90% for JPG, DOCX, PDF, and WEBP, and 85% for GIF. It does not affect BMP, PNG, or TIFF.
cache, cachelength Whether a repeated capture may be served from cache and its lifetime. Cache defaults and limits depend on account/package settings; documented minimum cache length is 15 minutes.
download Whether to automatically download or show the capture. Use the result method and download behavior that match the intended user flow.
background, transparent Background handling for supported document/image formats. Transparency applies only to PNG and TIFF. PDF background options are separate from image transparency.
country Capture location. Documented options include Singapore, UK, and US; default is the current fastest location.

A useful sizing example sets a viewport and an output size independently:

const options = {
  format: "webp",
  bwidth: 1440,
  bheight: 1000,
  width: 1200,
  quality: 82,
  delay: 1500
};

GrabzIt("YOUR_APPLICATION_KEY")
  .ConvertURL("https://example.com", options)
  .Create();

5. Useful capture controls

  • PDF output: use format: "pdf"; relevant documented options include pagesize, orientation, mleft, mright, and related margins, media (Print or Screen), title, background, and coverurl. PDF-related options are output-specific.
  • Interact before capture: the parameter reference includes CSS-selector controls such as click and hover. Use a delay or a readiness selector if the interaction needs time to change the page. The reference says only one of click, hover, or scroll can be specified at a time.
  • Hide common clutter: noads can hide adverts and nonotify can hide commonly found cookie notifications.
  • Resolve HTML resources: set address when supplied HTML refers to relative paths.
  • Secure or submit data: the library exposes methods including UseSSL(), Encrypt(), and AddPostVariable(name, value). Use these according to the official guidance for sensitive captures and request data; avoid embedding secrets in client code.
  • Generated element styling: displayid and displayclass can identify or style the inserted result. Error display styling options are also documented.

There are many less common options for document conversions, tables, proxy use, and exports. Their availability and valid combinations depend on output type; check the parameter reference instead of assuming an image option applies to PDF or another format.

6. Handle completion and save the file on your server

The browser API’s onfinish callback supplies a capture ID when the result is ready. Your application can send that ID to your own backend, which can then use a server-side GrabzIt API to retrieve the result and write it to storage. The server must keep the application secret private, validate and authorize the browser request, and verify that the capture ID belongs to the expected user or operation. The official support example demonstrates the capture-ID handoff pattern; the validation requirements are application security practice. [Events, Saving a JavaScript screenshot]

// Browser-side handoff. Implement /api/capture-ready on your own server.
GrabzIt("YOUR_APPLICATION_KEY")
  .ConvertURL("https://example.com", {
    format: "png",
    onfinish: async function (captureId) {
      const response = await fetch("/api/capture-ready", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ captureId })
      });
      if (!response.ok) {
        console.error("Server could not queue capture retrieval", response.status);
      }
    },
    onerror: function (message, code) {
      console.error("Capture failed", code, message);
    }
  })
  .Create();

The browser snippet is complete for the client side, but the backend endpoint is application-specific and must be implemented using a server-side GrabzIt SDK/API. Do not treat a capture ID as authorization. If exporting directly to remote storage from browser JavaScript, use a Secure Export URL so storage credentials are not exposed. [GrabzIt secure export]

7. cURL, Python, and Node.js examples

These are REST-style examples for the hosted conversion endpoint, not calls to the browser JavaScript library. Use server-side credentials appropriately and URL-encode values. The parameter reference and account setup determine the complete request and result retrieval workflow; do not copy these as a substitute for the browser library’s insertion methods.

cURL

curl -G "https://api.grabz.it/convert" \
  --data-urlencode "key=YOUR_APPLICATION_KEY" \
  --data-urlencode "format=png" \
  --data-urlencode "url=https://example.com" \
  -o capture.png

Python

import requests

response = requests.get(
    "https://api.grabz.it/convert",
    params={
        "key": "YOUR_APPLICATION_KEY",
        "format": "png",
        "url": "https://example.com",
    },
    timeout=90,
)
response.raise_for_status()
with open("capture.png", "wb") as output:
    output.write(response.content)

Node.js

const params = new URLSearchParams({
  key: process.env.GRABZIT_APPLICATION_KEY,
  format: "png",
  url: "https://example.com",
});

const response = await fetch(`https://api.grabz.it/convert?${params}`);
if (!response.ok) {
  throw new Error(`GrabzIt request failed: ${response.status}`);
}
const bytes = new Uint8Array(await response.arrayBuffer());
await import("node:fs/promises").then(fs => fs.writeFile("capture.png", bytes));

The endpoint shape follows GrabzIt’s official REST examples; verify the current API endpoint, synchronous/asynchronous behavior, and retrieval requirements for the account and output before using a server integration. [GrabzIt REST API security guidance]

8. Troubleshooting

Symptom Likely cause Fix
No result or domain-related failure The current website domain is not authorized for the application key. Add the exact domain in account settings, then reload the page from that domain.
Capture callback reports an error Invalid parameters, unsupported combinations, inaccessible target, or an account/package restriction. Log both message and code from onerror; simplify to a URL and format, then add options back one at a time. Check current parameter limits.
Screenshot is blank or content is missing Page content or assets were not ready, or resources require credentials/cannot be reached by the capture service. Use waitfor for visible content; use a modest delay for animation; make required assets reachable or use supported supplied HTML and an appropriate address.
Wrong framing or scale Viewport and output dimensions were mixed up. Set bwidth/bheight for page rendering and width/height for output size.
Relative images/styles are absent from HTML capture Relative URLs have no usable base address, or assets are private. Set address to the page/resource base and make the resources accessible to the renderer.
waitfor still captures too early The selector matched an element before its content finished loading, or the selector never became visible and the wait limit elapsed. Wait for a selector that represents actual readiness, not just a container; add a bounded delay only when needed.
Capture completes in the page but is not saved on the server onfinish only returns the capture ID; persistence requires a backend retrieval/export flow. Post the ID to a protected backend endpoint and retrieve the result through a server-side API.
Storage export exposes credentials A normal export URL is being used in browser JavaScript. Generate and use GrabzIt’s Secure Export URL. Never place storage username/password or secret keys in frontend code.
Request is slower than expected The page has heavy assets, a long delay, large viewport/output, or uncached rendering. Reduce dimensions to what the user needs, wait for a specific element, avoid unnecessary delays, and consider cache behavior for identical captures.

9. Performance, reliability, and cost considerations

  • Wait for a condition instead of guessing: a visible waitfor selector can avoid an arbitrary long delay. It has a documented 25-second maximum; use an explicit fallback/error state in your interface.
  • Control image size: larger browser and output dimensions can increase transfer size and processing work. Choose a viewport matching the page you need to represent and avoid requesting excess resolution.
  • Use caching intentionally: GrabzIt documents caching of matching captures to avoid consuming capture allowance again; set cache according to freshness needs and confirm account cache duration.
  • Handle asynchronous outcomes: use onstart, onfinish, and onerror to show state and log failures. For durable server persistence, perform retrieval on your backend.
  • Do not assume an SLA or fixed cost: this research does not establish latency, availability, or current package pricing. Check GrabzIt’s current account and pricing terms. No performance or reliability ranking is implied here.

10. Or skip the browser setup

ScreenshotNeo provides a single GET request for a URL and returns an image or PDF. The [ScreenshotNeo API documentation] lists its parameters and response behavior.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Cookie banners, popups, and chat widgets are removed before the shot; each cleanup step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits are never billed; response headers identify the page verdict and billing status.
  • An MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf.
  • 1,000 screenshots per month are free with no card; paid plans start at $5 for 3,000. Every feature is on every plan.

Learn about ScreenshotNeo, or sign up free for 1,000 screenshots a month with no card.

11. FAQ

Can I take a screenshot of a page after a user fills in a form?

Use ConvertPage() to submit the current page’s state for conversion. Check that required resources can be reached by the conversion service.

Does onfinish provide the image bytes?

No. It provides a capture ID. Use a result method such as DataURI() for a client-side data URL, or hand the ID to your backend for server-side retrieval.

Can I use the JavaScript API without exposing a key?

The browser API requires an application key in the client, so authorize its domain. Keep application secrets and storage credentials on the server.

Which method should I choose for a one-off preview?

Use ConvertURL for a hosted page or ConvertPage for the current page, then AddTo to place the preview in a specific element.

References