Book a call
Menu

Testing All 401 Pages at Phone Width: A Mobile Check Built on the Chrome DevTools Protocol

Happy Coders team1 Dec 202613 min read
Testing All 401 Pages at Phone Width: A Mobile Check Built on the Chrome DevTools Protocol

When we rebuilt happycoders.co.in as a static Next.js site, the build produced 401 pages: the new service pages, and more than three hundred blog posts carried over from WordPress. Before switching the live domain over, we wanted to know that every one of them worked on a phone. Not a sample of ten, not the home page and two articles, but all 401, at the two phone widths most of our visitors use.

Clicking through 802 pages in a phone emulator is not a test anyone does properly. So we wrote one: a single Node script that drives an ordinary Chrome over the DevTools protocol, opens four tabs, emulates a phone in each, and runs the same set of checks on every page. A full run takes a few minutes on a laptop. This post explains how it works, what each check catches and why, and the false alarms we had to remove before we could trust it. It found real problems on its first honest run, including two that no one had noticed on the old site in years.

Why not Lighthouse, or a screenshot service?

We use Lighthouse, and it answers a different question. It scores one page at a time on performance and best practice, and it is slow enough that running it 802 times is an afternoon. It also does not fail on the things that actually embarrass a site on a phone: a code block that pushes the whole page sideways, a menu that opens behind the content, an image that loads as an empty box.

Screenshot services have the opposite problem. They show you exactly what the page looks like, which is perfect for ten pages and useless for four hundred, because someone has to look at every image. We wanted something that could not get tired: a list of facts per page, measured in the browser, and a pass or a fail.

We also did not want a test framework. Playwright and Puppeteer are excellent, but this job needs about six DevTools commands. Speaking the protocol directly over a WebSocket kept the whole thing in one file with one dependency, and it runs against the Chrome already installed on the machine.

Driving Chrome without a framework

Chrome exposes everything DevTools can do on a local port when it starts with --remote-debugging-port. Give it a separate profile so the test never touches your own browsing session:

# A Chrome just for testing, with its own profile, controllable over a port
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \
  --remote-debugging-port=9340 \
  --user-data-dir="$HOME/.chrome-test-profile" \
  --no-first-run about:blank &

# Every page the static build produced
find out -name index.html | wc -l

The page list comes straight from the build output: every index.html under out/ becomes a URL. That matters more than it looks. A hand-maintained list of “pages to test” goes stale the day someone adds a page; the build output cannot. If a page exists, it is tested.

Each worker opens its own tab through the HTTP endpoint, then talks to it over the WebSocket that endpoint returns:

// Open a fresh tab and talk to it over the DevTools protocol.
async function tab() {
  const t = await (await fetch("http://127.0.0.1:9340/json/new?about:blank",
                               { method: "PUT" })).json();
  const ws = new WebSocket(t.webSocketDebuggerUrl);
  await new Promise((r) => ws.on("open", r));

  let id = 0; const pending = {}; const errors = [];
  ws.on("message", (raw) => {
    const m = JSON.parse(raw);
    if (m.id && pending[m.id]) { pending[m.id](m); delete pending[m.id]; }
    if (m.method === "Runtime.exceptionThrown")       // uncaught JS errors
      errors.push(m.params.exceptionDetails.text);
  });
  const send = (method, params = {}) => new Promise((r) => {
    const i = ++id; pending[i] = r; ws.send(JSON.stringify({ id: i, method, params }));
  });
  await send("Runtime.enable"); await send("Page.enable");
  return { send, errors };
}

// Then, per page:
await T.send("Emulation.setDeviceMetricsOverride",
             { width: 360, height: 800, deviceScaleFactor: 2, mobile: true });
await T.send("Page.navigate", { url: BASE + path });

Emulation.setDeviceMetricsOverride with mobile: true is the important call. It does more than resize the window: it sets the layout viewport, the device pixel ratio and touch-style behaviour the way a real phone would, so media queries and innerWidth report phone values. Resizing a desktop window to 390 pixels is not the same thing. When we first tried that with headless screenshots, pages looked cut off on the right. That was an artefact of the window size, not a bug in the site, and it cost us half an hour to prove it.

We test two widths. 360 is the narrowest common Android width and the one that breaks layouts first. 390 is the current iPhone width and what most of our visitors actually have. Four tabs run in parallel, each pulling the next page from a shared queue. Going past four made no difference on a laptop, because the bottleneck is the server and the network, not Chrome.

How the mobile test runs over every page
Four tabs pull from one queue of 802 jobs: every page at two widths.

The checks, and what each one is for

After each navigation the script waits for the page to settle, switches every loading="lazy" image to eager so nothing is skipped below the fold, waits for images to finish, then evaluates one function inside the page that returns a small object of facts:

// Runs inside the page. Returns one small JSON object of facts.
const W = innerWidth, past = [];
for (const el of document.querySelectorAll("body *")) {
  const cs = getComputedStyle(el);
  if (cs.display === "none" || cs.visibility === "hidden") continue;
  if (el.closest("pre, table, .skip, [aria-hidden=true]")) continue;   // allowed to scroll
  const r = el.getBoundingClientRect();
  if (r.width && (r.right > W + 1 || r.left < -1)) past.push(el.tagName);
}
const imgs = [...document.querySelectorAll("main img")];
return {
  sideways: document.documentElement.scrollWidth - W,
  pastEdge: past.length,
  broken:  imgs.filter(i => (i.complete && i.naturalWidth === 0)
                         || /^data:image[/]svg/.test(i.currentSrc)).length,
  noAlt:   imgs.filter(i => !(i.getAttribute("alt") || "").trim()).length,
  h1:      document.querySelectorAll("h1").length,
  tiny:    [...document.querySelectorAll("main p, main li, main a, main td")]
             .filter(e => e.offsetParent && parseFloat(getComputedStyle(e).fontSize) < 12).length,
  smallInputs: [...document.querySelectorAll("input:not([type=hidden]), select, textarea")]
             .filter(e => e.offsetParent && parseFloat(getComputedStyle(e).fontSize) < 16).length,
};

Each number maps to a problem a real visitor would notice.

Sideways scroll. If the document is wider than the viewport, the whole page wobbles left and right as the visitor scrolls. That is the most common mobile bug there is, and the single most irritating one. Any value above one pixel fails.

Elements past the edge. A page can avoid sideways scroll and still have content clipped, for example a button cut off by overflow: hidden on a parent. So we also walk every visible element and fail if any of them extends beyond the viewport. Some elements are supposed to scroll on their own: code blocks and wide tables, which sit in their own scroll container. Those are excluded, along with anything hidden from users.

Broken or placeholder images. Checking naturalWidth alone is not enough. On this site, WordPress content arrived with a theme’s lazy-loading placeholders: empty SVGs that “load” perfectly and show nothing. Checking currentSrc for a data URI SVG catches those as well.

Images without alt text. Screen readers, and search engines, need it. We count these rather than listing them, and fix them at build time from the post title when the author left the field blank.

Exactly one H1. Several old posts repeated their own title as an H1 inside the content, so the page had two. Not a visual problem, but a real one for screen reader users and for search engines.

Text under 12 pixels. Fine print that is readable on a desktop is unreadable on a phone held at arm’s length. We check paragraphs, list items, links and table cells inside the main content.

Form fields under 16 pixels. This one is specific to iPhones. When a visitor taps an input whose font size is below 16 pixels, Safari zooms the whole page in to make it readable, and then leaves it zoomed. It looks broken. The fix is one CSS rule; the hard part is knowing which forms need it.

JavaScript errors. Every uncaught exception on the page is collected through Runtime.exceptionThrown, and any error fails the page.

Testing the mobile menu like a thumb would

The checks above are about layout. The menu needed a different kind of test, because the bug we were worried about is invisible to a layout check. Earlier the same week, on our other site, a backdrop-filter on the header had turned the full-screen mobile menu into a strip a few pixels tall, because a filter creates a new containing block for position: fixed children. Every element was “on screen”. The menu just did not work.

So on the pages that matter most, the home page, services, contact and the blog index, the script opens the menu and then asks the browser what is actually under the user’s finger:

// Open the mobile menu, then ask what is really under the user's finger.
document.querySelector(".burger > summary").click();
await new Promise((r) => setTimeout(r, 400));
const panel = document.querySelector(".burger .panel").getBoundingClientRect();
const hit = document.elementFromPoint(innerWidth / 2, panel.top + 200);
return {
  height: Math.round(panel.height), viewport: innerHeight,
  onTop: !!(hit && hit.closest(".panel")),        // false = something covers it
  links: document.querySelectorAll(".burger .panel a").length,
};

elementFromPoint is the key call. It returns whatever would receive a tap at that coordinate, after every z-index, transform and overlay has been applied. If the answer is not inside the menu panel, then something is covering the menu, and a visitor tapping there would hit the page underneath. We also require the panel to be close to full height and to contain at least eight links, which catches the collapsed-strip bug directly.

The first run failed 800 pages, and almost none were real

The first full run reported a failure on nearly every page, and that was the most useful result of the whole exercise. A test that fails on everything is a test you will learn to ignore, so before fixing a single page we went through the failures and asked, for each rule, “would a visitor notice this?”

The biggest group was the “skip to content” link. Accessible sites put one at the very top of the page and keep it off-screen until it receives keyboard focus, usually with a large negative offset. To our edge check it looked like an element far off the left side of every page. It is supposed to be there, so it went into the exclusion list. Hidden decorative elements went the same way.

The second false alarm came from our own fix, later in the day. We tightened the broken-image rule with a regular expression, /^data:image\/svg/, inside the JavaScript string that the script sends into the page. The backslash was consumed by the string before Chrome saw it. That made the code a syntax error, and every page reported “could not load”. If every page fails at once, suspect the test before the site. Writing the slash as [/] removes the escaping problem entirely.

Real problems the mobile test found
None of these showed up in a ten-page spot check.

What it actually found

Once the noise was gone, the remaining failures were all real, and they fell into a handful of groups:

  • Labels in tiny type. Section kickers and card labels were styled below 12 pixels, which is fine on a desktop and hard to read on a phone. We raised them all to 12.
  • Two pages with two H1s. Old posts that repeated their title inside the content. The build now drops an H1 that matches the post title and demotes any other to an H2.
  • Form fields that made iPhones zoom. Forms inside a few carried-over pages used 14-pixel inputs. One rule, font-size: 16px on inputs inside article content, fixed every one.
  • Every article image blank. The lazy-loading placeholders described above. A build-time function now moves the real URLs back into src and srcset.
  • One genuinely dead image. A diagram hotlinked from another organisation’s website, which had since moved the file. The old theme’s lazy loader had hidden the failed request for years.

None of these would have shown up in a ten-page spot check. Two of them only appeared on old posts that nobody had opened on a phone since they were written.

Reading the report

The output is deliberately boring. While it runs, it prints a progress line every hundred pages with the number of problems so far. At the end it prints one line per failing page and width, with every reason for that page on the same line, then either ALL PASSED or a count of failures. A typical failure line reads: 360px /some-old-post/ — 2 H1; 1 text items under 12px (span.label 11px "Updated").

Two choices made that report useful. First, each reason carries a short sample of the offending element: its tag, its first class name, its size, and the first few words of its text. That is usually enough to find the CSS rule responsible without opening the page. Second, failures are grouped by page, not by rule. When the same rule fails on two hundred pages, the cause is almost always one shared component, and seeing the same sample text repeated down the list makes that obvious at a glance. When a rule fails on one page only, the cause is that page’s content, and it is a content fix, not a CSS fix.

We also kept the run honest about what it could not check. If a page fails to load twice, it is reported as “could not load” rather than silently skipped. A test that drops the pages it finds difficult will always look healthier than the site it is testing.

Running it before and after going live

We ran the full suite several times: against a preview copy of the site served from a subfolder, again after each round of fixes, and once more against the live domain right after it switched over. The preview run is the one that matters for fixing things. The live run catches the problems a preview cannot: a redirect rule that sends a page somewhere else, a CDN that serves a stale copy, a path that only works under the preview prefix. It passed all 802 loads.

Two habits made the live run trustworthy. First, the CDN in front of the site caches HTML, so after a deploy we load pages with a random query string when we need to be sure we are seeing the new version, not the cached one. Second, the deploy script refuses to upload a build with fewer pages than a fixed floor. A build that silently lost half its pages would otherwise pass a test that only checks the pages that exist.

What we would tell someone building the same thing

  • Derive the page list from the build, never from a hand-kept list. New pages are then tested on day one.
  • Emulate the device with Emulation.setDeviceMetricsOverride and mobile: true. A narrow desktop window is not a phone.
  • Measure facts in the page and decide in Node. One evaluate call per page returning a small object is fast, and it keeps the pass/fail rules in one readable place.
  • Every rule must answer “would a visitor notice?” If not, exclude it. Tolerating false alarms trains everyone to ignore the report.
  • Prove each rule fails on a real bug before trusting it to pass. Our placeholder-image rule, for example, had to fail on the blank articles before we believed its passes.
  • Test interactions by hit-testing, not by checking that elements exist. elementFromPoint tells you what a tap would actually do.

Questions we were asked

Why only two widths?

Because the bugs live at the narrow end. Anything that fits at 360 pixels almost always fits at 412 or 430. Tablets and desktops are better checked with a smaller sample, because their layouts change at breakpoints rather than failing gradually.

Does it replace testing on a real phone?

No. Emulation does not reproduce real touch scrolling, the on-screen keyboard pushing content up, or a slow mobile connection. Open the key pages on an actual Android phone and an iPhone before launch. The script makes sure there are no surprises left for that step, and that the other four hundred pages are covered too.

How long does a run take, and can it run in CI?

A few minutes for 802 loads over four tabs, most of it spent waiting for the network. It runs anywhere Chrome and Node do, so a CI job only needs to start Chrome headless with the debugging port, then run the script against the preview URL. It exits with a non-zero code on any failure.

We build fast, mobile-first websites and web apps for companies in the US, Singapore and worldwide, and we test them like this before they go live. See our React and Next.js work.

Keep reading

Related articles