Learn how to customize and manipulate serialized DOM using the domTransformation feature.
In certain scenarios, you may need to modify the DOM to ensure it renders correctly in Percy. For example, you might hide ad banners or adjust UI states that are not captured as expected. When Percy sends the serialized DOM to its backend for re-rendering across different browsers and devices, you can modify it by passing a domTransformation function. Learn more about the basics of Percy SDKs workflow by reviewing this guide.
The domTransformation function accepts documentElement as an argument and doesn’t require a return value. Check out the following examples to see how it works.
Examples
If you use the percy snapshot command, follow this configuration.
This feature requires Percy CLI v1.24.0 or higher.
It’s only available for per-snapshot configuration, and not global configuration.
Percy snapshot
snapshots:
- name: Example
url: https://example.com
widths: [1280]
domTransformation: |
(documentElement) => {
function changeHeader(root) {
documentElement.querySelector('h1').innerText = 'Changed using domTransformation'
}
changeHeader(documentElement);
}
If you’re using any SDKs then you can check the following SDK examples.
This applies to both BrowserStack SDK and Percy SDK.
Use percy_snapshot function if you’re using the Percy SDK for web projects. For Automate projects with the Percy SDK or when using the BrowserStack SDK, use percy_screenshotfunction.
// pass the function in string format as options to percySnapshot function
// you could use multiline string syntax that might be available in your language
domTransformation = (documentElement) => {
function updateLinks(root) {
root.querySelectorAll('.myLink').forEach(link => {
console.log(link);
// do stuff here
});
// we mark shadow host with following marker during serialisation
root.querySelectorAll('[data-percy-shadow-host]')
.forEach(
shadowHost => {
console.log(shadowHost);
if (shadowHost?.shadowRoot)
updateLinks(shadowHost.shadowRoot);
});
}
updateLinks(documentElement);
}
// in JS
domTransformation = domTransformation.toString()