Skip to content

Estrarre immagini di condivisione social e tag Open Graph

L'API HTMLRewriter di Bun può essere usata per estrarre efficientemente immagini di condivisione social e metadati Open Graph da contenuti HTML. Questo è particolarmente utile per costruire funzionalità di anteprima link, schede social media o web scraper. Possiamo usare HTMLRewriter per corrispondere selettori CSS a elementi HTML, testo e attributi che vogliamo elaborare.

ts
interface SocialMetadata {
  title?: string;
  description?: string;
  image?: string;
  url?: string;
  siteName?: string;
  type?: string;
}

async function extractSocialMetadata(url: string): Promise<SocialMetadata> {
  const metadata: SocialMetadata = {};
  const response = await fetch(url);

  const rewriter = new HTMLRewriter()
    // Estrai tag meta Open Graph
    .on('meta[property^="og:"]', {
      element(el) {
        const property = el.getAttribute("property");
        const content = el.getAttribute("content");
        if (property && content) {
          // Converte "og:image" in "image" ecc.
          const key = property.replace("og:", "") as keyof SocialMetadata;
          metadata[key] = content;
        }
      },
    })
    // Estrai tag meta Twitter Card come fallback
    .on('meta[name^="twitter:"]', {
      element(el) {
        const name = el.getAttribute("name");
        const content = el.getAttribute("content");
        if (name && content) {
          const key = name.replace("twitter:", "") as keyof SocialMetadata;
          // Usa dati Twitter Card solo se non abbiamo dati OG
          if (!metadata[key]) {
            metadata[key] = content;
          }
        }
      },
    })
    // Fallback ai tag meta regolari
    .on('meta[name="description"]', {
      element(el) {
        const content = el.getAttribute("content");
        if (content && !metadata.description) {
          metadata.description = content;
        }
      },
    })
    // Fallback al tag title
    .on("title", {
      text(text) {
        if (!metadata.title) {
          metadata.title = text.text;
        }
      },
    });

  // Elabora la risposta
  await rewriter.transform(response).blob();

  // Converte URL immagine relative in assolute
  if (metadata.image && !metadata.image.startsWith("http")) {
    try {
      metadata.image = new URL(metadata.image, url).href;
    } catch {
      // Mantiene l'URL originale se il parsing fallisce
    }
  }

  return metadata;
}
ts
// Esempio di utilizzo
const metadata = await extractSocialMetadata("https://bun.com");
console.log(metadata);
// {
//   title: "Bun — A fast all-in-one JavaScript runtime",
//   description: "Bundle, transpile, install and run JavaScript & TypeScript projects — all in Bun. Bun is a fast all-in-one JavaScript runtime & toolkit designed for speed, complete with a bundler, test runner, and Node.js-compatible package manager.",
//   image: "https://bun.com/share.jpg",
//   type: "website",
//   ...
// }

Bun a cura di www.bunjs.com.cn