
How to Inject Custom JavaScript and Hide Elements Before Capturing Screenshots

Snapshot Site Team
04 May 2025 - 01 Min read
In web automation and visual testing, control over the page content is critical before capturing screenshots.
By injecting JavaScript or hiding specific elements, you can customize the appearance of a webpage to:
- Remove ads, popups, or cookie banners
- Change styles (e.g., highlight important sections)
- Ensure a clean and professional screenshot result
Why Inject JavaScript Before a Screenshot?
- Highlight Key Areas: Modify styles dynamically before capture.
- Clean Visuals: Hide unwanted elements like notifications and modals.
- Dynamic Testing: Adjust layouts for different conditions or devices.
- Increase Automation Accuracy: Capture exactly what matters without distractions.
Example: Modify Wikipedia Before Taking a Screenshot
Here's an example using Java and AsyncHttpClient to call the Snapshot Site API, inject JavaScript, and hide elements:
import org.asynchttpclient.*;
public class ScreenshotExample {
public static void main(String[] args) throws Exception {
AsyncHttpClient client = new DefaultAsyncHttpClient();
client.prepare("POST", "https://screenshot-snapshot-site2.p.rapidapi.com/api/v2/screenshot")
.setHeader("x-rapidapi-key", "YOUR_API_KEY")
.setHeader("x-rapidapi-host", "screenshot-snapshot-site2.p.rapidapi.com")
.setHeader("Content-Type", "application/json")
.setHeader("Accept", "application/json")
.setBody("""
{
"url": "https://wikipedia.org",
"format": "png",
"width": 1280,
"height": 720,
"delay": 0,
"fullSize": false,
"hideCookie": false,
"javascriptCode": "document.body.style.color = '#fd7e14'; var elements = document.querySelectorAll('a'); [].slice.call(elements).forEach(function(elem) { elem.style.color = '#fd7e14'; });",
"hide": "#js-link-box-en, #js-link-box-fr"
}
""")
.execute()
.toCompletableFuture()
.thenAccept(System.out::println)
.join();
client.close();
}
}