DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
full-page screenshot

How to Capture a Full-Page Screenshot With Sticky Elements in Safari Using Java

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

SafariDriver does not turn Selenium’s ordinary screenshot command into a full-document image. The WebDriver screenshot command covers the current top-level viewport, so a reliable Safari-and-Java workflow is to capture successive viewports, then stitch them into one image. To keep fixed navigation bars, sticky headings, and floating buttons from appearing repeatedly, leave them visible in the first frame and hide or mask them before later captures.

This guide shows the setup, a complete Java example, decisions for sticky elements, failure recovery, and a no-browser alternative using ScreenshotNeo.

What Safari’s screenshot command actually captures

The W3C WebDriver specification defines the Take Screenshot command as capturing the top-level browsing context’s initial viewport. Selenium exposes that operation through TakesScreenshot and getScreenshotAs; SafariDriver is one of the documented implementations. An element screenshot is similarly limited to the element’s visible region after Selenium scrolls it into view.

Therefore, this code captures only what is currently visible:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
byte[] png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);

It does not guarantee a document-height image. A full-page result requires a second layer: scroll, wait for layout and lazy content, capture, and combine the images.

Prerequisites and SafariDriver setup

  • A Mac with Safari enabled for WebDriver automation.
  • A Java project containing Selenium client libraries compatible with your Java version.
  • The Safari browser version and macOS version you intend to support. Sticky behavior and screenshot dimensions can vary between releases, so record both in repeatable jobs.

Apple documents Safari WebDriver for Selenium clients that support Java. Selenium’s Safari guide shows the SafariOptions/SafariDriver pattern and notes that safaridriver ships with the operating system. Enable it once from Terminal:

#1 Best Overall
Apple 2026 MacBook Neo 13-inch Laptop with A18 Pro chip: Built for AI and Apple Intelligence, Liquid Retina Display, 8GB Unified Memory, 256GB SSD Storage, 1080p FaceTime HD Camera; Blush
  • AN AMAZING MAC AT A SURPRISING PRICE — With an incredibly portable and durable aluminum design, up to 16 hours of battery life,* and the A18 Pro chip, MacBook Neo is ready to go wherever school takes you.
  • FOUR STUNNING COLORS. ONE DURABLE DESIGN — Choose from four beautiful colors — Silver, Blush, Citrus, or Indigo — each with a color-coordinated keyboard. And MacBook Neo is made with a durable recycled aluminum enclosure that helps it reach 60 percent recycled content by weight — the most ever in any Apple product.*
  • FLY THROUGH EVERYDAY ASSIGNMENTS — Whether you’re cramming for finals, using Apple Intelligence* to summarize class notes, creating presentations, or even playing the latest Apple Arcade game,* MacBook Neo delivers the performance and AI capabilities you need to get things done.
  • UP TO 16 HOURS OF BATTERY LIFE — MacBook Neo delivers all day battery life, so you can power through from early morning classes to late night study sessions without worrying about plugging in.
  • A VIBRANT 13-INCH DISPLAY* — The gorgeous Liquid Retina display on MacBook Neo supports 1 billion colors, so photos and videos pop and text is crisp for easy reading.
safaridriver --enable

On managed Macs, an administrator policy may control this setting. Start with a normal Selenium session and confirm that Safari opens before adding stitching logic.

How the scroll-and-stitch algorithm works

  1. Open the URL and wait for the page’s important content to settle.
  2. Measure document height and viewport width/height in CSS pixels.
  3. Capture the top viewport with sticky elements visible.
  4. Scroll down by nearly one viewport at a time. A deliberate overlap helps align seams and hides tiny rounding differences.
  5. After the first frame, hide or mask selected sticky and fixed elements, then capture the remaining viewports.
  6. Draw each image onto a canvas at its scroll offset, using the screenshot’s pixel-to-CSS scale.
  7. Recheck the final image for repeated controls, lazy images, animations, and sections that loaded after the initial height measurement.

The sample below implements that policy. It is intentionally adaptable: selectors for sticky elements differ from site to site, and nested scrolling containers require a different scroll target.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Complete Java example for a Safari full-page capture

The following Selenium 4 example writes a PNG. It keeps the first viewport unchanged, hides selected elements in subsequent frames, uses an 80-CSS-pixel overlap, and places each capture at its actual scroll position.

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariOptions;
import org.openqa.selenium.WebDriver;

import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class SafariFullPageScreenshot {
    private static final String URL = "https://example.com";
    private static final int OVERLAP_CSS_PX = 80;

    public static void main(String[] args) throws Exception {
        SafariOptions options = new SafariOptions();
        WebDriver driver = new SafariDriver(options);
        JavascriptExecutor js = (JavascriptExecutor) driver;
        List frames = new ArrayList<>();
        boolean stickyHidden = false;

        try {
            driver.get(URL);
            waitForPage(js, 1500);

            while (true) {
                long scrollY = ((Number) js.executeScript("return window.scrollY;")).longValue();
                long docHeight = ((Number) js.executeScript(
                    "return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);"
                )).longValue();
                long viewportHeight = ((Number) js.executeScript("return window.innerHeight;")).longValue();

                byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
                BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
                frames.add(new Frame(scrollY, image));

                if (!stickyHidden) {
                    // Replace these selectors with the page's actual fixed/sticky controls.
                    js.executeScript("""
                        const selectors = ['header.sticky', '.fixed-nav', '[data-sticky]', '.chat-widget'];
                        for (const selector of selectors) {
                          document.querySelectorAll(selector).forEach(el => {
                            el.dataset.safariShotOriginalVisibility = el.style.visibility;
                            el.style.visibility = 'hidden';
                          });
                        }
                    """);
                    stickyHidden = true;
                    waitForPage(js, 150);
                }

                long nextY = Math.min(scrollY + viewportHeight - OVERLAP_CSS_PX,
                                      Math.max(0, docHeight - viewportHeight));
                if (nextY <= scrollY) break;
                js.executeScript("window.scrollTo(0, arguments[0]);", nextY);
                waitForPage(js, 300);
            }

            BufferedImage output = stitch(frames, js);
            ImageIO.write(output, "png", new File("safari-full-page.png"));
        } finally {
            // Restore styles before closing if the session will be reused.
            if (stickyHidden) {
                js.executeScript("""
                    document.querySelectorAll('[data-safari-shot-original-visibility]').forEach(el => {
                      el.style.visibility = el.dataset.safariShotOriginalVisibility;
                      delete el.dataset.safariShotOriginalVisibility;
                    });
                """);
            }
            driver.quit();
        }
    }

    private static void waitForPage(JavascriptExecutor js, long milliseconds) throws InterruptedException {
        Thread.sleep(milliseconds);
        // This waits for document readiness, but network requests and animations may still exist.
        js.executeScript("return document.readyState");
    }

    private static BufferedImage stitch(List<Frame> frames, JavascriptExecutor js) {
        Frame first = frames.get(0);
        double scale = first.image.getWidth() /
            ((Number) js.executeScript("return window.innerWidth;")).doubleValue();
        long cssHeight = ((Number) js.executeScript(
            "return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);"
        )).longValue();
        int width = first.image.getWidth();
        int height = (int) Math.ceil(cssHeight * scale);
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = result.createGraphics();
        for (Frame frame : frames) {
            int y = (int) Math.round(frame.scrollY * scale);
            graphics.drawImage(frame.image, 0, y, null);
        }
        graphics.dispose();
        return result;
    }

    private record Frame(long scrollY, BufferedImage image) {}
}

Change URL and the sticky selectors before running. The code assumes the page scrolls in the top-level window and that screenshots keep a consistent width. For production jobs, add explicit waits for a meaningful selector instead of relying only on sleeps.

Choosing what sticky elements should look like

Keep the element once

Keeping the header in the first frame makes the image look like a normal page capture while avoiding repeated headers lower down. This is usually best for site previews and documentation.

Rank #2
Sale
Apple 2026 MacBook Air 13-inch Laptop with M5 chip: Built for AI, 13.6-inch Liquid Retina Display, 16GB Unified Memory, 512GB SSD, 12MP Center Stage Camera, Touch ID, Wi-Fi 7; Midnight
  • BUILT FOR COLLEGE. AND BEYOND — MacBook Air with the M5 chip packs blazing speed and powerful AI capabilities into an incredibly portable design. And with up to 18 hours of battery life,* this thin and light powerhouse is ready to take on almost any major, just about anywhere.
  • TEAR THROUGH TOUGH ASSIGNMENTS — With its faster CPU and unified memory, the M5 chip delivers even more performance and fluidity across apps, making multitasking and creative workflows smooth and responsive. A powerful Neural Engine and next-generation GPU with Neural Accelerators give you a powerful platform for AI.
  • MAKE QUICK WORK OF YOUR TO-DO LIST — Apple Intelligence helps you write, express yourself, and get things done effortlessly — whether it’s for school or everyday life. With groundbreaking privacy protections, it gives you peace of mind that no one else can access your data — not even Apple.*
  • UP TO 18 HOURS OF BATTERY LIFE — MacBook Air delivers incredible battery life with amazing performance, so you can power through a full day of classes without worrying about plugging in.
  • A BRILLIANT 13.6-INCH DISPLAY* — The gorgeous Liquid Retina display on MacBook Air supports 1 billion colors, making photos and videos pop with rich contrast and sharp detail, and text appears supercrisp. So everything — from class presentations to movies to games — looks truly stunning.

Hide it after the first frame

Set visibility:hidden or inject a temporary CSS rule after the first capture. Visibility preserves layout, reducing vertical jumps. Restore the original inline style in a finally block.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Mask it instead

If a sticky bar is part of the design, draw a solid rectangle over its repeated copies during compositing. Masking is safer when hiding the element causes reflow, but the mask must match the bar’s pixel height.

When selectors are not enough

Some widgets are inside an iframe or shadow root, and some pages move an element between containers as you scroll. You may need to switch into the iframe, inject CSS into its document, or identify the element by geometry. A selector that matches a normal header does not automatically match a browser-level overlay.

Handling lazy loading, changing heights, and seams

  • Lazy images: wait after every scroll and verify that image dimensions have settled. A page can grow after images decode, so recalculate document height in the loop.
  • Animations: pause them with temporary CSS or capture at a deterministic point. Otherwise, adjacent frames may show different positions.
  • Overlap: the sample overlays frames at their scroll offsets. If a site paints a sticky element over the overlap, hide it before later captures or crop that strip manually.
  • Device pixel ratio: Safari may return screenshot pixels at a higher scale than CSS pixels. The sample derives a scale from screenshot width divided by window.innerWidth; retain that conversion when calculating output dimensions.
  • Nested scroll areas: if the article is inside an element with overflow:auto, scroll that element and measure its scrollHeight instead of using window.scrollTo.
  • Very tall pages: a single in-memory BufferedImage can consume substantial RAM. Stitch in bands or write a tiled format when page height exceeds your process budget.

Common failures and fixes

Safari does not start

Run safaridriver --enable, check that Safari is installed and unlocked for automation, and verify that your Selenium client supports the installed Safari version. Record macOS, Safari, Java, and Selenium versions when reporting the problem.

Rank #3
Apple 2026 MacBook Neo 13-inch Laptop with A18 Pro chip: Built for AI and Apple Intelligence, Liquid Retina Display, 8GB Unified Memory, 256GB SSD Storage, 1080p FaceTime HD Camera; Indigo
  • AN AMAZING MAC AT A SURPRISING PRICE — With an incredibly portable and durable aluminum design, up to 16 hours of battery life,* and the A18 Pro chip, MacBook Neo is ready to go wherever school takes you.
  • FOUR STUNNING COLORS. ONE DURABLE DESIGN — Choose from four beautiful colors — Silver, Blush, Citrus, or Indigo — each with a color-coordinated keyboard. And MacBook Neo is made with a durable recycled aluminum enclosure that helps it reach 60 percent recycled content by weight — the most ever in any Apple product.*
  • FLY THROUGH EVERYDAY ASSIGNMENTS — Whether you’re cramming for finals, using Apple Intelligence* to summarize class notes, creating presentations, or even playing the latest Apple Arcade game,* MacBook Neo delivers the performance and AI capabilities you need to get things done.
  • UP TO 16 HOURS OF BATTERY LIFE — MacBook Neo delivers all day battery life, so you can power through from early morning classes to late night study sessions without worrying about plugging in.
  • A VIBRANT 13-INCH DISPLAY* — The gorgeous Liquid Retina display on MacBook Neo supports 1 billion colors, so photos and videos pop and text is crisp for easy reading.

The output contains only the first screen

That is expected from a single getScreenshotAs call. Confirm that the loop advances window.scrollY, that the page is the top-level scroller, and that the output writer is called only after all frames are collected.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Headers appear on every section

Expand the selector list to include the actual sticky or fixed nodes. Inspect computed styles while scrolling; a class named “sticky” is not required for CSS position:sticky.

Blank bands or misaligned seams

Recalculate height after lazy content loads, use an overlap, and place images using their measured scroll offsets rather than a fixed frame index. Check that all screenshots have the same width and scale.

Content is missing below the fold

Scroll in smaller increments, wait for the page’s loading marker or target selector, and disable virtualization if the site supports it. Some applications render only the visible rows; no screenshot stitcher can recover rows the page never inserted into the DOM.

Rank #4
Apple 2026 MacBook Neo 13-inch Laptop with A18 Pro chip: Built for AI and Apple Intelligence, Liquid Retina Display, 8GB Unified Memory, 256GB SSD Storage, 1080p FaceTime HD Camera; Citrus
  • AN AMAZING MAC AT A SURPRISING PRICE — With an incredibly portable and durable aluminum design, up to 16 hours of battery life,* and the A18 Pro chip, MacBook Neo is ready to go wherever school takes you.
  • FOUR STUNNING COLORS. ONE DURABLE DESIGN — Choose from four beautiful colors — Silver, Blush, Citrus, or Indigo — each with a color-coordinated keyboard. And MacBook Neo is made with a durable recycled aluminum enclosure that helps it reach 60 percent recycled content by weight — the most ever in any Apple product.*
  • FLY THROUGH EVERYDAY ASSIGNMENTS — Whether you’re cramming for finals, using Apple Intelligence* to summarize class notes, creating presentations, or even playing the latest Apple Arcade game,* MacBook Neo delivers the performance and AI capabilities you need to get things done.
  • UP TO 16 HOURS OF BATTERY LIFE — MacBook Neo delivers all day battery life, so you can power through from early morning classes to late night study sessions without worrying about plugging in.
  • A VIBRANT 13-INCH DISPLAY* — The gorgeous Liquid Retina display on MacBook Neo supports 1 billion colors, so photos and videos pop and text is crisp for easy reading.

Cookie dialogs or chat widgets cover content

Dismiss them before the first capture or add their selectors to the temporary-hide list. Do not hide an element that is required to trigger consent when the page cannot otherwise be used.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

SafariDriver versus Playwright Java

SafariDriver plus scroll-and-stitch is the choice when the requirement is the Safari browser supplied with macOS. Playwright Java documents a full-page screenshot option, but that documentation does not establish that it drives Safari’s installed safaridriver. Confirm the required browser and rendering engine before treating the two workflows as interchangeable.

Decision point SafariDriver and stitching Playwright Java full-page option
Actual Safari WebDriver session Yes, through SafariDriver Not established by the cited Java screenshot documentation
Full-page assembly Your code controls scrolling, overlap, and sticky policy Provided as a documented option
Sticky-element treatment Hide, mask, or keep elements according to your selectors Verify behavior for the browser and page you target
Portability Safari/macOS-specific rendering Depends on the browser engine selected

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server when you need an image without maintaining Safari automation. A single GET request can return PNG, JPEG, WebP, or PDF, with options for full-page capture, lazy-image loading, CSS-selector element capture, custom CSS and JavaScript, waits, device presets, dark mode, retina scale, request blocking, cookies, headers, user agents, timezone, geolocation, caching, signed links, asynchronous jobs, and bulk capture.

Best Value
Sale
Apple 2026 MacBook Pro Laptop with Apple M5 Pro chip with 18-core CPU and 20-core GPU: Built for AI, 16.2-inch Liquid Retina XDR Display, 24GB Unified Memory, 1TB SSD, Wi-Fi 7; Space Black
  • FAST RUNS IN THE FAMILY — The 16-inch MacBook Pro with the M5 Pro or M5 Max chip brings next-generation speed and powerful on-device AI to personal, professional, and creative tasks. With all-day battery life, double the starting storage,* and a breathtaking Liquid Retina XDR display, it’s pro in every way.*
  • BUCKLE UP — Along with a next-generation CPU, faster unified memory, and up to 2x faster SSD storage,* M5 Pro and M5 Max feature a more powerful GPU with a Neural Accelerator built into each core, delivering faster AI performance and on-device training capabilities. So you can blaze through demanding workloads at mind-bending speeds.
  • BUILT FOR AI — Apple silicon, and every major component that powers it, is designed to run demanding on-device AI workloads like LLM inference and training. And Apple Intelligence helps you write, express yourself, and get things done effortlessly with groundbreaking privacy protections at every step.*
  • ALL-DAY BATTERY LIFE — MacBook Pro delivers the same exceptional performance whether it’s running on battery or plugged in.*
  • MACOS RUNS APPS FAST — All your go-to apps run lightning fast in macOS, including built-in apps like FaceTime and Messages. Plus, built-in virus protection and free software updates help keep your Mac running smoothly and securely.

It removes cookie/consent banners, newsletter popups, and chat widgets before the capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for AI clients such as Claude and Cursor.

See the ScreenshotNeo documentation for parameters and authentication. cURL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

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)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.

Frequently Asked Questions

Can Selenium’s SafariDriver capture a full page with one command?

No. Its standard screenshot call captures the current top-level viewport, so a document-height image needs scrolling and stitching or a separate full-page service.

Should a sticky header be visible in the final image?

Choose a policy per page: keep it in the first frame, hide it after the first frame, or mask repeated copies during compositing.

Why does the stitched image have different-sized sections?

Safari screenshot pixels can be scaled relative to CSS pixels. Use the screenshot-width-to-window-innerWidth ratio and place frames using their measured scroll offsets.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Will this work for a page that scrolls inside a div?

Not unchanged. Measure and scroll the nested container, capture its visible region, and adapt the height and offset calculations to that element.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.