Skip to main content

Code injection

Injecting code into a page can help ensure the consistency of screenshots. For example, if a screenshot is taken while assets are not fully loaded, it can result in a flaky test.

Here are some functions that we recommend running in the tested pages and waiting for them to resolve before taking a screenshot:

Inject Styles

Inject styles to hide elements and fix unstable rendering:

function injectStyles(document) {
const css = document.createElement("style");
css.type = "text/css";
css.textContent = cssText;

Ensure No Busy State

Check for the presence of [aria-busy="true"] elements on the page, which can indicate that a page is still loading:

async function ensureNoBusy() {
const checkIsVisible = (element) =>
element.offsetWidth ||
element.offsetHeight ||

return [...document.querySelectorAll('[aria-busy="true"]')].every(
(element) => !checkIsVisible(element)

Wait for Fonts

Wait for all fonts to be loaded:

function waitForFonts() {
return document.fonts.status === "loaded";

Wait for Images

Wait for all images to be loaded:

async function waitForImages() {
return Promise.all(
.filter((img) => !img.complete)
(img) =>
new Promise((resolve) => {
img.onload = img.onerror = resolve;