Code to Extract the Site Thumbnail Image for Twitter or Facebook

CK CK 3788 
Created at  
396 0 0

To extract a site thumbnail (often referred to as Open Graph or Twitter Card image) from an HTML string, we need to look for specific <meta> tags that are commonly used for social media sharing on platforms like Facebook and Twitter. These tags include Open Graph (og:image) and Twitter Card (twitter:image) meta tags.

Open Graph is a protocol originally created by Facebook that allows web pages to become rich objects within social media platforms. By using Open Graph meta tags in the HTML <head> of a webpage, developers can control how their content is displayed when shared on social media networks such as Facebook, LinkedIn, Twitter, and others that support the protocol.

Twitter Card is a metadata protocol used by Twitter to display rich media (like images, videos, and previews) when a link to a webpage is shared on the platform. By adding specific meta tags to the <head> section of a webpage's HTML, developers can control how content appears in tweets, making it more engaging and visually appealing.

 

Code to Extract the Thumbnail Image for Twitter or Facebook:

function getSiteThumbnailFromHtml(html) {
  // Create a DOM parser to parse the HTML string
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');

  // Look for Open Graph image or Twitter Card image meta tags
  const ogImage = doc.querySelector('meta[property="og:image"]');
  const twitterImage = doc.querySelector('meta[name="twitter:image"]');
  
  // Return the content of the first found image
  if (ogImage) {
    return ogImage.getAttribute('content');
  } else if (twitterImage) {
    return twitterImage.getAttribute('content');
  } else {
    return null; // No thumbnail found
  }
}

// Example HTML input (replace with your HTML content)
const htmlText = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta property="og:image" content="https://example.com/og-image.jpg">
  <meta name="twitter:image" content="https://example.com/twitter-image.jpg">
  <title>Example Page</title>
</head>
<body>
  <h1>Hello, World!</h1>
</body>
</html>
`;

// Extract the site thumbnail
const thumbnailUrl = getSiteThumbnailFromHtml(htmlText);
console.log(thumbnailUrl); // Outputs: "https://example.com/og-image.jpg"

How It Works:

  1. DOMParser: Converts the HTML string into a DOM object.
  2. meta[property="og:image"]: Searches for the Open Graph image meta tag, which is commonly used by Facebook and other social platforms.
  3. meta[name="twitter:image"]: Searches for the Twitter Card image meta tag, which is specifically used by Twitter.
  4. getAttribute('content'): Retrieves the image URL from the content attribute of the first found meta tag.
  5. Returns the Image URL: The function returns the first image it finds from the two tags, prioritizing the Open Graph image (og:image) if both are present.

 

Explanation of Meta Tags:

  • Open Graph (og:image): Used by Facebook and other platforms like LinkedIn to define the image that will be used when a page is shared on social media.

    <meta property="og:image" content="https://example.com/og-image.jpg">
    
  • Twitter Card (twitter:image): Used by Twitter to specify the image that should be displayed in a tweet when a link to the page is shared.

    <meta name="twitter:image" content="https://example.com/twitter-image.jpg">
    

Notes:

  • If both meta tags are present, the Open Graph image will take priority in the function. You can modify the logic if you want to prioritize Twitter's image or handle both in some other way.
  • If neither tag is found, the function returns null.
Tags Meta Tags Open Graph Site Metadata Site Thumbnail Twitter Card Facebook X
Comments 0
Similar posts
  1. What is Twitter Cards?
    405
  2. What is OpenGraph?
    367
  3. JavaScript Code to Get Page Keywords
    353
  1. Tailwind CSS and shadcn/ui for React App with Charts and Graphs
    1,049
  2. HTML NoIndex: Keep Pages Off Search
    1,499
  3. JavaScript to disable Screen Saver or Power Saving Mode
    509
  4. Improving SEO with image-sitemap
    1,183
  5. Making HTML Tables Responsive on Mobile: Addressing Text Overflow
    783
  6. How do we make better SEO with schema.org?
    428
  7. A Javascript code that returns Monthly Mortgage Payment and Tax
    1,266
  8. A simple JavaScript snippet to copy a string to the clipboard
    1,058
  9. Dynamic JSON Editor based in HTML/JavaScript
    514
  10. How to post content (image or video) to Instagram using the Instagram Graph API
    6,412
  11. Font name correctly having the same width space
    1,229
  12. JavaScript Algorithms
    722
  13. GraphQL Tutorial on CentOS 7: From Installation to Deployment
    564
  14. Capture all browser console logs including errors for debugging
    2,192
  15. Simple asynchronous/synchronous $.ajax() example using jQuery to make an HTTP GET request
    863
  16. JavaScript Code to Get the Page Title
    340
  17. JavaScript Code to Get Meta Description from HTML
    398
  18. Javascript code to extract favicon URL
    404
  19. RSS to Array in JavaScript
    2,169
  20. Javascript function to convert sitemap.xml to array
    602
  21. Understanding Elasticsearch from Installation to Trouble Shooting
    915
  22. IndexNow for better SEO
    321
  23. Enhancing SEO for Single Page Applications: Implementing Dynamic URL Updates
    1,043
  24. Method to ignore JavaScript Errors globally instead of try... catch for each of cases
    973
  25. Method to catch the browser console log and errors for remote web debugging
    2,191
  26. Atlassian Jira Ticket API Response Example
    2,807
  27. Three different type of Word-Wrap options in HTML CSS
    1,189
  28. JavaScript code to load XML Document
    604
  29. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    599
  30. Equal Height Blocks in Bootstrap with JavaScript
    713
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,248
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    107
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    116
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    230
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233