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

Direct answer: inject the script with stringByEvaluatingJavaScriptFromString:, wait for a page-specific signal that the visual change is ready, then render the UIWebView’s visible hierarchy into a bitmap using drawViewHierarchyInRect:afterScreenUpdates:. Check its Boolean result before using the image. UIWebView is deprecated, so maintained apps should use WKWebView’s asynchronous takeSnapshot API instead.

What the capture sequence must guarantee

JavaScript evaluation and screenshot capture are separate operations. A synchronous return from JavaScript means the script call completed; it does not prove that images, CSS transitions, network requests, or later callbacks have finished painting. A reliable workflow therefore has four stages:

  1. Run the DOM mutation or other script.
  2. Coordinate with a page-specific readiness signal, such as a callback you control or a state check.
  3. On the main thread, render the web view at the intended visual state.
  4. Validate the result and handle incomplete or failed captures.

Do not substitute an arbitrary sleep for readiness coordination. Apple’s API references do not define a universal delay that works for every page or iOS version.

Legacy UIWebView implementation (Objective-C)

Apple documents UIWebView as deprecated and directs developers to WKWebView. If you must maintain legacy code, the following pattern captures the web view’s visible bounds after your readiness condition has fired. The APIs are documented in Apple’s UIWebView reference and drawHierarchy(in:afterScreenUpdates:).

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.
#1 Best Overall
Guermok Video Capture Card, 4K USB3.0 HDMI to USB C, 1080P 60FPS & 2K 30FPS
  • 【1080P 60FPS Video Capture Card】 This HDMI game capture card is based on USB3.0 high speed transmission port, input resolution up to 4K@30HZ, output resolution up to 2K@30Hz or 1920×1080@60Hz. Type c and USB interface can meet most of the devices in daily life. Easily meet the online capture, real-time recording, online meetings, live gaming and other functions, so you have a better visual enjoyment. Note: For capture use only; requires capture software to function and is not intended for direct screen casting to a monitor or TV
  • 【Ultra Low Latency Screen Sharing】 HDMI capture card is made of good quality aluminum alloy with strong heat dissipation, allowing you to enjoy ultra low latency while live gaming or video recording or live streaming, avoiding blue screens and lag. This HDMI to USBC capture card supports easy recording of good quality audio or HD video and transferring it to your computer or streaming platform, allowing you to record 60 fps HD video directly on your hard drive and real-time preview
  • 【Plug and Play, Easy to Carry】 This HDMI 1080P video capture card does not require any additional drivers or external power supply, just plug and play for fast capture. The capture card is small and lightweight, so you can put it in your bag for emergencies, making it very portable for outdoor live streaming. It's also a great way to share content in game recording, video conference, video recorder and online teaching
  • 【Wide Compatibility USB Capture Card】 Easily streams to Facebook, Youtube or Twitch. With the connection, this HDMI to USB C/3.0 video capture devices can be working on several Operating Systems and various software: Windows 7/ 8/ 10, Mac OS or above, Linux, Android, Laptop, Xbox One, PS3/PS4/PS5, Camera, DVDs, Set Top Box, Webcame, DSLR, Switch/Switch 2, TV BOX, HDTV, Potplayer/VLC, ZOOM, OBS Studio etc.
  • 【Package Content & Note】 1x HD Audio Capture Card , 1x USB 3.0 to USB C Adapter (A-side 3.0, B-side 2.0), 1x user manual. Please note that you need to restart the OBS Studio software after the audio setup is complete, otherwise it will result in no sound output. When using an adapter, if the device is recognized as USB 2.0, try using the other side with the USB-C port. Simply flip the capture card and reconnect it to be recognized as USB 3.0

1. Inject the JavaScript

NSString *script = @"
  (function() {
    var panel = document.querySelector('#status-panel');
    if (!panel) return 'missing-panel';
    panel.classList.add('ready-for-capture');
    panel.setAttribute('data-capture-state', 'ready');
    return 'ready';
  }())";

NSString *result = [webView stringByEvaluatingJavaScriptFromString:script];
if ([result isEqualToString:@"missing-panel"]) {
    // Report that the expected page element was not found.
}
// Continue only after your page-specific readiness condition is true.

stringByEvaluatingJavaScriptFromString: returns a string synchronously. That return value is useful for checking the script’s immediate result, but it is not a rendering-complete notification.

2. Wait for the visual state you intend to capture

If you own the page, have the page call a native bridge or expose a state that the app can poll after images and asynchronous work are ready. If the script starts an animation, wait for the animation’s completion event or a deterministic final state. If content arrives from the network, wait for the page’s own loaded-state signal rather than assuming navigation completion or JavaScript evaluation is sufficient.

3. Draw the visible hierarchy into an image

- (UIImage *)captureVisibleUIWebView:(UIWebView *)webView
                               error:(NSError **)error {
    __block UIImage *capturedImage = nil;
    __block BOOL complete = NO;

    void (^captureBlock)(void) = ^{
        CGSize size = webView.bounds.size;
        if (size.width <= 0 || size.height <= 0) {
            return;
        }

        UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
        complete = [webView drawViewHierarchyInRect:webView.bounds
                                  afterScreenUpdates:YES];
        capturedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    };

    if ([NSThread isMainThread]) {
        captureBlock();
    } else {
        dispatch_sync(dispatch_get_main_queue(), captureBlock);
    }

    if (!complete || capturedImage == nil) {
        if (error) {
            *error = [NSError errorWithDomain:@"ScreenshotCapture"
                                          code:1
                                      userInfo:@{
                NSLocalizedDescriptionKey: @"The UIWebView hierarchy did not produce a complete image."
            }];
        }
        return nil;
    }
    return capturedImage;
}

The graphics context uses a scale of 0.0, allowing UIKit to select the screen’s native scale. The receiver is the UIWebView, so the image contains the web content visible in that view. A containing native view should be captured only when its surrounding controls are intentionally part of the output.

Rank #2
Video Capture Card, 4K USB3.0 HDMI to USB C, 1080P60FPS HDMI Capture Card for Streaming, Gaming, Video Recording Compatible with Switch, Xbox, PS4/5, OBS,iPad Mac OS Windows,Camera, Zoom(Silver)
  • 【4K HDMI Input, 2K@30Hz Recording】Powered by a true USB 3.0 high-speed interface, the capture card supports up to 4K@30Hz HDMI input and records at 2K@30Hz or 1080P@60Hz. Perfect for gamers, streamers, and professionals who need crisp, smooth video for live streaming, gameplay recording, or online meetings.
  • 【Ultra Low Latency Screen Sharing】Built with a premium aluminum alloy shell and advanced chipset for stable heat dissipation, ensuring ultra-low latency transmission. Capture high-quality video and dual-channel audio in real time—no lag, no frame drop—ideal for Twitch, YouTube, or OBS streaming.
  • 【Easy Plug and Play, Compact & Portable】No driver or external power required—just plug and play via USB 3.0 or Type-C connection to your Windows or macOS computer. Lightweight and compact design makes it easy to carry for outdoor streaming, live shows, or mobile recording setups.
  • 【Wide Compatibility & Multi-Device Support】Compatible with Windows 7 8 10 11, macOS, Linux,Android and supports most popular software such as OBS, Zoom, VLC, Twitch Studio, and more. Works seamlessly with PS4, PS5, Xbox, Switch, DSLR cameras, TV boxes, and other HDMI-output devices for streaming to YouTube, Twitch, etc.
  • 【What You Get】Includes: HDMI Capture Card, USB 3.0 to USB-C Adapter, User Manual. Tips: Make sure your tablet’s OTG function is enabled before connecting. Test your HDMI device with a monitor first to confirm video and audio output, then connect to the Video Capture Card for recording.

What the Boolean result means

UIKit’s hierarchy-drawing method renders a snapshot of the complete hierarchy as visible onscreen into the current context. Its return value is false when image data is missing for any view in the hierarchy. Treat false as an incomplete capture, not as a successful image that merely needs a different file format.

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

Save or display the image

UIImage *image = [self captureVisibleUIWebView:webView error:&error];
if (image) {
    NSData *png = UIImagePNGRepresentation(image);
    [png writeToFile:path atomically:YES];
}

Use JPEG or another representation only after you have a valid image. A valid bitmap still represents the visible view bounds; it is not automatically a full-document export.

Why afterScreenUpdates does not solve readiness

Passing YES asks UIKit to include recent view updates. It does not wait for arbitrary JavaScript, network activity, image decoding, or CSS animation to finish. Conversely, passing NO can omit recent changes. Use YES when the purpose is to include your latest mutation, but synchronize page state separately.

Rank #3
Sale
UGREEN 2K@30Hz 1080P 60FPS Video Capture Card 4K Input HDMI to USB 3.0
  • 2K 30FPS & 1080p 60FPS HDMI Capture Card: The 4K@30Hz input and 2K@30Hz output resolutions offer dual benefits. The high input resolution preserves original video quality for post-production editing, while the 2K output provides an optimal balance between clarity and compatibility. At the same time, this HDMI to USB-C capture card is also backward compatible with 1080p 60FPS, to fulfill a variety of daily needs. Note: Ensure your HDMI source device and the capture device support 2K resolution
  • Low Latency 5 Gbps High Data Transfer Speed: With high-speed USB 3.0 technology for optimal performance and low delay, you can easily stream video from the Switch/Switch 2/PS4/PS5 to Twitch, YouTube, Facebook, Twitter, OBS, Potplayer, and VLC on a computer. It's also backward compatible with USB 2.0. Note: This capture card for streaming only supports HDMI input sources, as well as iPadOS devices need to be updated to 17 or higher to use it
  • USB A and USB C ports: Featuring both USB-A and USB-C interfaces, this streaming capture card ensures broad compatibility with modern devices, including smartphones, laptops, tablets, desktops, and Quest 3. Perfect for multi-scenario streaming—whether you're broadcasting camera footage, mobile gaming, or PC live streams. Note: This capture card only supports unidirectional signal flow—HDMI input to USB output
  • Universal Compatibility: This Driver-Free HDMI capture card for streaming supports Windows 11/10/8.1/7, MacOS, Linux, and phones/tablets. This capture card effortlessly livestreams gameplay from Switch, Switch 2, PS4/PS4 Pro/PS5 (Disable HDCP mode), Xbox Series X, and Meta Quest 3/2 directly to your iPad, laptop, or PC. Fully support OBS Studio, XSplit, PotPlayer, QuickTime Player, and more for streaming, recording, editing, and high-res video transfer. Note: iPadOS 17 or later is required for USB-C iPad compatibility. Switch / Xbox / PS5/ PS4 work fine when HDCP is turned off
  • Durable USB Capture Card: The aluminum alloy casing easily dissipates heat and is lightweight while effectively shielding against EMI, ensuring stable signal transmission. The built-in cable features 26AWG (2C) + 30AWG (1P) tinned copper conductors, ensuring excellent conductivity and corrosion resistance, enhancing durability, and reducing signal loss
Question What the API establishes What it does not establish
Did JavaScript run? The evaluation call returned a value or completed its callback. That asynchronous page work has completed.
Were recent UIKit updates considered? afterScreenUpdates:YES includes recent view updates when drawing. That every web resource or animation is finished.
Is the hierarchy complete? The Boolean result reports missing image data. That a false result can be safely ignored.
Is the whole document captured? The visible web view bounds are rendered. A full-page or offscreen webpage export.

Preferred migration: WKWebView

For apps running iOS 8 and later, Apple recommends WKWebView instead of UIWebView. See the WKWebView class reference. WKWebView provides asynchronous JavaScript evaluation and a purpose-built snapshot method documented at takeSnapshot(with:completionHandler:).

Objective-C WKWebView pattern

WKWebView *webView = self.webView;
NSString *script = @"document.querySelector('#status-panel').classList.add('ready-for-capture');";

[webView evaluateJavaScript:script completionHandler:^(id value, NSError *error) {
    if (error) {
        NSLog(@"JavaScript failed: %@", error);
        return;
    }

    // Invoke this only after the page-specific readiness signal,
    // not merely because evaluation returned.
    dispatch_async(dispatch_get_main_queue(), ^{
        WKSnapshotConfiguration *configuration = [WKSnapshotConfiguration new];
        configuration.rect = webView.bounds;

        [webView takeSnapshotWithConfiguration:configuration
                             completionHandler:^(UIImage *image, NSError *snapshotError) {
            if (snapshotError) {
                NSLog(@"Snapshot failed: %@", snapshotError);
                return;
            }
            // Use image here: save it, display it, or pass it to another API.
        }];
    });
}];

takeSnapshot generates a platform-native image asynchronously. WKSnapshotConfiguration lets you specify the portion to capture. The completion handler supplies either an image or an error, so retain neither assumption nor placeholder image when an error is reported.

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.

Choosing between the two APIs

Axis UIWebView WKWebView
Lifecycle Deprecated legacy API. Apple’s supported replacement.
JavaScript stringByEvaluatingJavaScriptFromString:. evaluateJavaScript:completionHandler:.
Capture Caller creates a graphics context and draws the visible hierarchy. Asynchronous takeSnapshot returns a native image.
Region Receiver’s visible bounds. Region configured through WKSnapshotConfiguration.
Completion Synchronous Boolean indicating hierarchy completeness. Asynchronous image/error completion.
Readiness Both require page-specific coordination when injected code starts asynchronous visual work.

Visible view versus full-page capture

The documented UIWebView drawing method captures the hierarchy as visible onscreen. Increasing the web view’s content size or scroll position does not turn this API into a documented full-page exporter. If you need a document-length image, design a separate paging or rendering workflow and verify how it behaves with fixed-position elements, lazy-loaded images, and memory limits. WKWebView’s configurable snapshot rectangle gives more control over the capture region, but you should still validate the output for your content and supported OS versions.

Rank #4
WARRKY Video Capture Card with 100W Power Delivery, USB 3.0 1080P 60HZ HD
  • [Exclusively Design] The L-shaped USB-C connector fits perfectly with Quest and iPad, while the extended cable design allows quick access to the connection port without removing the headset. Elevate your content with the WARRKY capture card through 4K@30fps input and 1080P@60fps recording. The YUY2 format delivers richer colors than MJPEG, eliminating banding with vibrant gradients for true-to-life streaming.
  • [100W High Speed Charging] Engineered for uninterrupted creativity, this capture card unleashes 100W ultra-fast charging through PD3.0 technology - simultaneously powering your Quest 3 and iPad while capturing gameplay or live streams. Never let a low battery interrupt your winning streak: the intelligent power management sustains stable voltage even during graphic-intensive VR battles or multi-hour broadcasts.
  • [Engineered for Excellence] The WARRKY capture card redefines reliability with aerospace-grade aluminum housing and braided nylon cabling, housing the flagship MS2130 chipset that achieves industry-leading 0.05s transmission latency. Precision-machined aluminum alloy dissipates heat 40% faster than plastic shells, maintaining stability during VR marathons, while triple-shielded nylon cables resist tangling across mobile studio setups.
  • [Universal Compatibility] The capture card is compatible with Switch, PS5/4, cameras, laptops, and tablets. It supports a wide range of capture software and platforms like HDMI Link, MoniCon, OBS Studio, QuickTime, and YouTube, and works with Windows 7/8/8.1/10, MacOS, Linux, Android, and iPadOS 17+. Enjoy seamless integration and exceptional performance across almost all your devices.
  • [WARRKY] We are committed to delivering exceptional quality products that combine sophisticated design with affordable pricing, offering you the best solutions for seamlessly connecting your work and life. If you have any issues, please reach out to us at your convenience. Your satisfaction is our top priority.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting failed or stale screenshots

The screenshot does not show the JavaScript change

  • Cause: capture ran immediately after evaluation while the page was still rendering.
  • Fix: wait for a page-owned callback, DOM state, image-load condition, or animation completion, then capture on the main thread with afterScreenUpdates:YES.

drawViewHierarchyInRect: returns false

  • Cause: image data is missing for at least one view in the hierarchy, or the hierarchy is being captured in an invalid/incomplete state.
  • Fix: treat the result as a failure, verify the web view has non-zero bounds, ensure capture occurs on the main thread, retry only after the page is stable, and log the failure instead of silently saving the image.

The output is blank

  • Cause: the web view has not laid out, navigation has not produced content, the view is hidden, or the page failed to load.
  • Fix: check bounds and visibility, observe navigation errors, wait for the page’s readiness signal, and inspect the generated image before publishing it.

A popup, overlay, or native control appears unexpectedly

  • Cause: hierarchy drawing includes everything visible in the receiver’s hierarchy.
  • Fix: capture the web view rather than a larger container, or deliberately hide application-owned overlays before the readiness signal and restore them afterward.

Animation frames vary between captures

  • Cause: the capture occurs at an uncontrolled animation time.
  • Fix: pause or disable the animation in page CSS/JavaScript, or capture from an explicit completion event. A fixed sleep is not a general solution.

WKWebView completion returns an error

  • Cause: the web view cannot produce the requested snapshot at that moment, or its configuration/region is invalid for the current state.
  • Fix: inspect the error, confirm the view is loaded and sized, use a valid snapshot rectangle, and retry after page-specific readiness rather than immediately looping.

Performance and reliability practices

  • Perform UIKit view access and hierarchy drawing on the main thread.
  • Capture only the required region to reduce bitmap memory.
  • Release the graphics context promptly and avoid retaining large images longer than necessary.
  • Use deterministic page markers so automated tests can distinguish “script evaluated” from “visual state ready.”
  • Record the OS version, web view type, bounds, readiness state, and API result when diagnosing intermittent failures.
  • Test pages with slow images, redirects, iframes, fixed headers, video, and CSS animations; their behavior can differ from a static local page.

Or skip the browser setup

If your requirement is a server-side screenshot rather than an in-app UIWebView bitmap, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF. It accepts cookie/consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status.

See the ScreenshotNeo API documentation for all options. A cURL request is:

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}`);

Its 63 options include full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, PDF settings, custom CSS and JavaScript, pre-capture clicks, hidden selectors, selector/delay/network-idle waits, request and resource blocking, headers/cookies/user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, selectable cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, an OpenAPI specification, and compatibility with parameter names used by other screenshot APIs. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

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

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

Best Value
Anker USB C to HDMI Adapter (4K@60Hz), USB Type C to HDMI Cable Adapter
  • The Anker Advantage: Join the 80 million+ powered by our leading technology.
  • Vivid Video: The HDMI adapter lets you connect to any TV or display with an HDMI port to stream video in up to 4K resolution.
  • Plug and Play: Instantly turn your laptop’s USB-C port into an HDMI port, with no installation necessary. This product does not support charging or Power Delivery (PD).
  • Premium Construction: A lightweight aluminum casing allows for greater heat dissipation, while the reinforced braided-nylon cable is designed to withstand the twists and tugs of daily use.
  • Compatibility: Supports USB-C DP Alt mode, USB4, and Thunderbolt connections.

FAQ

Can I capture the entire UIWebView document with this method?

No. The documented hierarchy drawing captures what is visible in the web view’s onscreen bounds. A full-document result needs a separate, purpose-built workflow.

Should I call the screenshot method from a background queue?

No. Dispatch UIKit view inspection and drawing to the main thread, then move file encoding or other non-UI processing off the main thread when appropriate.

Does a JavaScript completion value prove that the screenshot is ready?

No. It proves only that the evaluation call returned. Use a readiness condition tied to the page’s actual visual state.

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

What should new applications use instead of UIWebView?

WKWebView. Apple marks UIWebView deprecated and documents WKWebView as the replacement, with asynchronous JavaScript evaluation and snapshot APIs.

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.