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;
document.body.appendChild(css);
}

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) =>
Boolean(
element.offsetWidth ||
element.offsetHeight ||
element.getClientRects().length
);

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(
Array.from(document.images)
.filter((img) => !img.complete)
.map(
(img) =>
new Promise((resolve) => {
img.onload = img.onerror = resolve;
})
)
);
}