Automated ad-placement audits with Playwright: screenshots, slot counts and fill status
Key takeaways
- Playwright is Microsoft's open-source browser automation library (Apache-2.0); version 1.65.1 was current on npm in November 2026.
- page.route() can abort requests to Google's ad domains, so an audit can inspect your ad markup and layout without requesting a single ad.
- A layout audit can count ins.adsbygoogle slots, measure how many sit in the first mobile viewport, flag slots with no reserved height and check that ads.txt is reachable.
- data-ad-status is set only after an ad request completes, so fill status is better collected from real visitors with a MutationObserver than from automated page loads.
- Automated audits should never click ads or load monetized pages repeatedly with ads enabled.

Playwright lets you audit your ad placements automatically: open every template on an emulated phone, count AdSense slots, measure how many sit above the fold, flag slots that reserve no height, verify ads.txt and save full-page screenshots. The key design choice is to block Google’s ad domains during the audit, so you check your own markup without generating a single ad request.
What should an automated ad audit check?
Checks that are objective and fully under your control:
| Check | Why it matters |
|---|---|
Number of ins.adsbygoogle slots per template |
catches templates that accidentally doubled units |
| Slots in the first mobile viewport | content should come first; see ad placement policies |
Slots with zero height and no min-height |
a source of layout shift when the ad arrives |
Hidden slots (display: none) |
hiding units that serve ads is not something to do by accident |
ads.txt status and a google.com ... DIRECT line |
a missing file puts earnings at risk |
| Full-page screenshot per template and device | lets a human review spacing and labels quickly |
Things an automated audit cannot judge well: whether a placement is “misleading”, whether content quality is sufficient, or how an auction behaves. Keep humans on those.
Why block ad requests during the audit?
Every page load with live ad code requests ads. An audit that runs nightly over dozens of URLs would generate a steady stream of automated ad requests on monetized pages. You do not need them to check markup, so block them. Playwright’s network documentation shows how to abort matching requests with page.route():
await page.route(/googlesyndication\.com|doubleclick\.net|adservice\.google\./, (route) => route.abort());
Side effects you should expect: the AdSense script does not run, so Auto ads never inserts units, and no data-ad-status attribute appears. Your audit sees exactly what your HTML and CSS produce, which is the part you control. For testing that involves real ads, read testing ads safely first.
The audit script
Install Playwright in a separate folder (version 1.65.1 at the time of writing) and its Chromium build:
npm init -y
npm install playwright
npx playwright install chromium
Save this as audit-ads.mjs:
// audit-ads.mjs: node audit-ads.mjs https://www.example.com/ https://www.example.com/article/
import { chromium, devices } from 'playwright';
import { mkdir } from 'node:fs/promises';
const urls = process.argv.slice(2);
await mkdir('shots', { recursive: true });
const browser = await chromium.launch();
const context = await browser.newContext({ ...devices['iPhone 13'] });
const page = await context.newPage();
// Block Google ad requests: this audit checks your markup and must not request ads.
await page.route(/googlesyndication\.com|doubleclick\.net|adservice\.google\./, (r) => r.abort());
for (const url of urls) {
await page.goto(url, { waitUntil: 'load' });
const viewportHeight = page.viewportSize().height;
const slots = await page.locator('ins.adsbygoogle').evaluateAll((els) =>
els.map((el) => {
const r = el.getBoundingClientRect();
const cs = getComputedStyle(el);
return {
slot: el.dataset.adSlot || null,
format: el.dataset.adFormat || null,
top: Math.round(r.top + scrollY),
height: Math.round(r.height),
minHeight: cs.minHeight,
hidden: cs.display === 'none',
};
})
);
const origin = new URL(url).origin;
const adsTxt = await context.request.get(origin + '/ads.txt');
const adsTxtBody = adsTxt.ok() ? await adsTxt.text() : '';
const report = {
url,
slots: slots.length,
aboveFold: slots.filter((s) => s.top < viewportHeight).length,
noReservedHeight: slots.filter((s) => s.height === 0 && s.minHeight === '0px').length,
adsTxtStatus: adsTxt.status(),
adsTxtHasGoogle: /^\s*google\.com\s*,\s*pub-\d+\s*,\s*DIRECT/im.test(adsTxtBody),
details: slots,
};
console.log(JSON.stringify(report, null, 2));
const name = new URL(url).pathname.replace(/[^a-z0-9]+/gi, '_') || 'home';
await page.screenshot({ path: `shots/${name}.png`, fullPage: true });
}
await browser.close();
Run it with one URL per template:
node audit-ads.mjs https://www.example.com/ https://www.example.com/some-article/
We tested this script with Playwright 1.65.1 against a local test page containing two manual ad units (one with min-height: 250px, one without) and a one-line ads.txt. The relevant part of the output was:
{
"slots": 2,
"aboveFold": 0,
"noReservedHeight": 1,
"adsTxtStatus": 200,
"adsTxtHasGoogle": true
}
That is the expected result for that test page: the second slot reserves no space, so it would push content down when an ad arrives.
Add a desktop pass
Many sites change their ad layout above a breakpoint: sidebars appear, in-content units change size, anchor formats differ. Run the same loop in a second context with a desktop viewport, using the viewport option from the emulation guide:
const desktop = await browser.newContext({ viewport: { width: 1366, height: 768 } });
const desktopPage = await desktop.newPage();
await desktopPage.route(/googlesyndication\.com|doubleclick\.net|adservice\.google\./, (r) => r.abort());
Note that routes belong to a page or context, so the block must be set again for the new context. Save screenshots under a different folder, or add the device name to the file name, so mobile and desktop results never overwrite each other. Compare slot counts between the two: a template that shows four units on desktop and four stacked units on a phone usually needs a different mobile layout.
How the pieces work
- Device emulation.
devices['iPhone 13'], from Playwright’s emulation guide, sets viewport, user agent, scale factor and touch. Add a second context with a desktop viewport for wide layouts. - Slot measurement.
locator().evaluateAll()runs once in the page and returns plain data, which is faster than one call per element. - ads.txt.
context.request.get()fetches the file outside the page, following redirects. The regular expression only checks that a Google DIRECT line exists; for full syntax rules see ads.txt syntax. - Screenshots.
page.screenshot({ fullPage: true })is the call shown in Playwright’s screenshots guide. Element screenshots (locator.screenshot()) are handy to capture the area around one slot.
Turning the audit into a regression test
Once the output looks right, add assertions so a deploy fails when something changes unexpectedly:
- Store expected values per template: number of slots, maximum
aboveFold,noReservedHeightequal to 0. - Fail the script (
process.exit(1)) when a value differs. - Run it in CI against a staging build, ideally one where the ad script is not included at all.
- Keep screenshots as build artifacts so a reviewer can compare before and after.
Playwright’s test runner (@playwright/test) offers visual comparisons with toHaveScreenshot(), but ad slots make pixel comparisons noisy. Compare layout numbers rather than pixels, or mask the ad containers.
How do I track fill status without a bot?
AdSense adds a data-ad-status attribute to each ins element after the ad request completes, with values documented by Google, such as “filled” and “unfilled” (details in unfilled ad slots). Because the attribute only exists after a real request, measure it where real requests already happen: on your visitors’ page views.
This observer reports each slot’s status once per page view to an endpoint you control:
const seen = new Set();
const mo = new MutationObserver((records) => {
for (const r of records) {
const el = r.target;
const status = el.getAttribute('data-ad-status');
const key = el.getAttribute('data-ad-slot') || 'auto';
if (!status || seen.has(el)) continue;
seen.add(el);
navigator.sendBeacon('/ad-status', JSON.stringify({ page: location.pathname, slot: key, status }));
}
});
document.querySelectorAll('ins.adsbygoogle').forEach((el) =>
mo.observe(el, { attributes: true, attributeFilter: ['data-ad-status'] }));
We verified it in Playwright on a local page where a script set the attribute: it sent one beacon per slot with the expected status. It only watches slots present when it runs; Auto ads units inserted later need an extra observer on the document with childList: true, subtree: true. Aggregate the results per slot and page template to find units that rarely fill, and compare with your AdSense reports before removing anything. Google also notes that the attribute is not added for units served through a cross-domain window.
Common mistakes
- Leaving ads enabled in nightly audits. Block ad domains or audit a build without ad code.
- Scripting clicks anywhere near ads. Even “testing” clicks are invalid activity.
- Auditing only the home page. Article and category templates usually carry most of the units.
- Testing desktop only. Most ad layout issues appear at phone widths.
- Trusting
waitUntil: 'networkidle'on ad pages. Ad-heavy pages rarely go idle; useloadplus explicit waits for your own elements.
Pair this audit with Lighthouse CI for performance budgets and with real-user data for what visitors actually experience.
Open-source tools mentioned
| Tool | Licence |
|---|---|
| Playwright | Apache-2.0 |
Frequently asked questions
Is it safe to run Playwright on pages that show my AdSense ads?
It is safe when the script blocks Google's ad domains with page.route(), because no ad request leaves the browser. Running automated browsers with ads enabled creates ad requests from a bot, which you should avoid on monetized pages. Never script clicks on ads, and keep any ads-on check to rare manual sessions in a normal browser.
Why does my audit find zero ad slots on pages with Auto ads?
Auto ads places its units with JavaScript after the AdSense script loads. If the audit blocks ad requests, the script never runs and no Auto ads slots are inserted, so only manual ins.adsbygoogle units in your HTML are counted. To audit Auto ads layouts, rely on the AdSense preview tools and on real-user data rather than an automated browser.
Can Playwright check whether my ad slots are filled?
Only by letting ads load, because AdSense sets data-ad-status on the ins element after the ad request completes. That means automated ad requests. A safer method is a small MutationObserver on your live pages that reports each slot's data-ad-status from real visitors to your own endpoint, as shown in this guide.
Which device should I emulate for ad audits?
Use at least one phone and one desktop profile. Playwright ships device descriptors such as devices['iPhone 13'] that set viewport, user agent, device scale factor and touch. Most layout problems with ads (slots above the content, stacked units, unreserved height) show up first on narrow screens.
Sources
- Network | Playwright · Playwright
- Screenshots | Playwright · Playwright
- Emulation | Playwright · Playwright
Related guides
- Unfilled AdSense ad slots: reading data-ad-status and handling blank spaces cleanly
Why AdSense slots stay blank, how data-ad-status reports filled, unfilled and unfill-optimized units, and how to hide or replace empty slots within policy.
- AdSense ad placement policies: labels, accidental clicks, navigation, pop-ups and floating ads
The AdSense ad placement rules in one place: allowed ad labels, encouraging clicks, ads near navigation, floating boxes, pop-ups, refresh and overlap, with fixes.
- Clicking your own AdSense ads: why it is prohibited and how to test ads safely
Clicking your own AdSense ads is prohibited for any reason. How to check ads and layouts without clicking, what to tell staff and family, what to do after a slip.
- Lighthouse and Lighthouse CI on ad-heavy pages: setup, budgets and measuring third-party impact
Run Lighthouse and Lighthouse CI on pages with AdSense: a tested config, third-party budgets, an ads-on vs ads-off comparison and how to read the results.