跳到正文
DEV Community· Design Den Solutions·· 2 小時前AI 評分45

如何用建置時檢查找出網站社交分享圖片的 metadata 問題

Our og:image was a 200x60 logo on every page. Here is the check that would have caught it.

AI 導讀

網站把 200x60 的標誌圖片設為 15 個頁面的 og:image,卻同時宣告 twitter:card 為 summary_large_image,導致分享預覽的圖片比例和尺寸不符。作者以約 40 行 JavaScript 編寫建置時檢查,驗證圖片尺寸、比例及必要 metadata,讓問題在部署前令建置失敗。

正文

Every page of our site declared twitter:card as summary_large_image and pointed og:image at the same file: a 200x60 logo, 5 KB, on white.

Those two declarations contradict each other. A large card asks the platform to render a wide image; a 200x60 asset is a wordmark. When someone pasted our link into a chat, the platform had to choose between a blurred upscale and a letterboxed strip, and the card looked like an afterthought.

This is not a design opinion. It is a metadata contract, and it is checkable in about forty lines of JavaScript. Here is the audit, the failure modes it exposes, and the build-time assertion that should catch it before deployment.

Orange 3D picture frame on a dark charcoal surface holding one tiny postage-stamp photo, with the Design Den Solutions logo above the headline "Your share card is mostly empty" and the contact line +91 98721 90965 | www.designdensolutions.com.

What a link scraper actually reads

When a link is pasted into LinkedIn, Slack, WhatsApp, Facebook or X, the preview is not produced by your browser. A crawler fetches the page HTML over HTTP and parses:

  • og:title, og:description, og:url
  • og:image (and optionally og:image:width, og:image:height, og:image:alt)
  • twitter:card, twitter:title, twitter:image, twitter:site

Then, separately, it downloads the image and caches it. Three consequences follow:

  1. No JavaScript runs. Anything injected by your SPA after hydration is invisible to the preview.
  2. The image fetch is a second request, often from a datacenter IP with no cookies. A CDN rule or bot challenge that only affects unknown user agents can silently break the image while the page itself is fine.
  3. Previews are cached. Fixing the tag does not fix the card until the cache expires or you force a re-scrape.

So the failure is not "our image is small". The failure is that the preview is assembled from three separate fetches, and any one of them can be wrong without the page looking wrong.

The audit

Fifteen public pages, one curl loop, parse the head, count the declarations:

for p in index about services branding web-development \
         app-development digital-marketing graphic-design social-media \
         portfolio insights contact faq why-us case-studies; do
  curl -sL "https://www.designdensolutions.com/$p.html" \
    | grep -o -i '<meta[^>]*\(og:\|twitter:\)[^>]*>'
done

The result:

Finding Pages
Declare og:image = /assets/images/logos/logo.png 15 of 15
Declare twitter:card=summary_large_image 15 of 15
Declare og:image:width or og:image:height 0 of 15
Declare og:image:alt 0 of 15
Declare twitter:site 0 of 15

And the referenced file:

HTTP 200, image/png, 5,017 bytes, 200x60 px

One asset, fifteen pages, a 3.33:1 wordmark behind a declaration that asks for a wide editorial card.

Nothing here throws an error. Every page was valid HTML, every status code was 200, and the site rendered perfectly. The defect only exists at the seam between the page and someone else's renderer.

Why 200x60 fails specifically

Aspect ratio. Cards are designed near 1.91:1 (the 1200x630 convention). A 3.33:1 image does not fill that box, so the consumer either crops the sides off your wordmark or pads it with a background colour you did not choose.

Absolute size. A card rendered at 600 px wide upscales a 200 px image roughly threefold. Wordmarks with fine strokes blur first.

Platform minimums. Each consumer has its own threshold below which it drops the image entirely or degrades to a small summary card. A 200x60 asset sits under several of those thresholds, so the same page can produce a large card on one platform and a text-only card on another.

No declared dimensions. Without og:image:width and og:image:height, the crawler must download the file before it can reserve layout. Some clients render the preview in stages; a missing size is one more reason for a collapsed or jumping card.

No og:image:alt. Alt on a share card is read by accessibility tooling in some consumers. It is also the only place to describe an image that contains text, which every branded card does.

No twitter:site. The card loses the attribution line, so the preview does not visibly belong to the account that posted it.

A build-time assertion

A one-off audit decays. The useful artefact is a check that fails the build when a page's card contract breaks. Node, no dependencies:

// check-og.mjs
const pages = ["/", "/about.html", "/web-development.html" /* ... */];

function pngSize(buf) {
  if (buf.slice(1, 4).toString() !== "PNG") return null;
  return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
}
function jpegSize(buf) {
  let i = 2;
  while (i < buf.length) {
    if (buf[i] !== 0xff) { i++; continue; }
    const marker = buf[i + 1];
    if (marker >= 0xc0 && marker <= 0xcf) {
      return { h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) };
    }
    i += 2 + buf.readUInt16BE(i + 2);
  }
  return null;
}

const failures = [];
for (const path of pages) {
  const url = new URL(path, "https://www.designdensolutions.com");
  const html = await (await fetch(url)).text();
  const meta = (name) =>
    (html.match(new RegExp(
      `<meta[^>]+(?:property|name)=["']${name}["'][^>]+content=["']([^"']*)`, "i")) || [])[1];

  const img = meta("og:image");
  if (!img) { failures.push(`${path}: missing og:image`); continue; }
  if (!/^https:\/\//.test(img)) failures.push(`${path}: og:image not absolute`);

  if (meta("twitter:card") === "summary_large_image") {
    const buf = Buffer.from(await (await fetch(img)).arrayBuffer());
    const size = pngSize(buf) ?? jpegSize(buf);
    if (!size) failures.push(`${path}: cannot read image size`);
    else {
      if (size.w < 1200 || size.h < 600) failures.push(`${path}: ${size.w}x${size.h} too small`);
      const ratio = size.w / size.h;
      if (ratio < 1.7 || ratio > 2.1) failures.push(`${path}: ratio ${ratio.toFixed(2)}`);
    }
  }
  if (!meta("og:image:alt")) failures.push(`${path}: missing og:image:alt`);
  if (!meta("twitter:site")) failures.push(`${path}: missing twitter:site`);
}

if (failures.length) { console.error(failures.join("\n")); process.exit(1); }

Checked against our site, this script exits non-zero on all fifteen pages - 60 failures, four per page - which is the point: the assertions describe the contract, not the current markup. Wire it into CI next to your link checker and the class of bug stops recurring.

What to fix, in order

  1. Generate one card per page, 1200x630, 1.91:1, under ~300 KB. Text on the card should be a page headline, not a full sentence.
  2. Declare the size with og:image:width and og:image:height, and add og:image:alt.
  3. Keep og:url canonical and absolute, one value per page.
  4. Serve the image from a host that does not challenge unknown user agents. Test with a plain curl -A facebookexternalhit.
  5. Re-scrape after deploying. LinkedIn Post Inspector, Facebook Sharing Debugger and the X card validator each show exactly what they fetch; stale caches are indistinguishable from broken markup until you look.
  6. Assert it in CI, or the next template refactor will quietly point every page at the logo again - as ours did.

The part that generalises

Share cards are the clearest example of a broader category: metadata that only exists for machines you do not control. It has no visual regression test, no 200-status safety net, and no error surface in your own browser. The only way to know is to fetch the page the way the crawler does and check the contract.

We build and audit sites this way - markup first, then the consumers of that markup. If your share previews look thin, that is usually a website-development problem before it is a marketing one: website development in Chandigarh and Mohali.

Prepared with AI assistance for Design Den Solutions. The cover illustration is AI-generated; the official Design Den Solutions logo is composited unchanged. The measurements above come from a public fetch of our own site on 24 November 2026, not from client data.

來源:DEV Community · dev.to