Skip to main content

Overview

The caching system stores API responses in memory to provide instant access when users revisit tabs or search terms. It uses a simple Map-based cache with automatic eviction to prevent unbounded memory growth.

Cache Structure

The cache is initialized as a JavaScript Map at the module level:
content.js:12
let cache = new Map(); // key: `${lang}:${term}:${tab}`
Cache Key Format:
{language}:{searchTerm}:{tabId}
Examples:
  • en:Albert Einstein:summary
  • ar:الفيزياء:define
  • en:JavaScript:facts
The cache is cleared when the user changes their preferred language setting, ensuring language-specific results are always accurate.

Cache Configuration

The cache has a fixed size limit:
content.js:22
const CACHE_SIZE = 30;
Why 30 entries?
  • Balances memory usage with performance
  • Covers typical browsing session needs
  • Each entry contains JSON data (usually 1-5KB)
  • Total memory footprint: ~30-150KB

Cache Key Generation

The getCacheKey() function creates consistent keys:
content.js:171-173
function getCacheKey(term, tab) {
  return `${currentLanguage}:${term}:${tab}`;
}
Includes:
  • currentLanguage - Ensures language-specific content
  • term - The cleaned search term
  • tab - Tab ID to separate different content types
The search term should be cleaned with cleanSearchTerm() before generating cache keys to ensure consistent matching.

Reading from Cache

The getFromCache() function retrieves cached data:
content.js:175-177
function getFromCache(term, tab) {
  return cache.get(getCacheKey(term, tab));
}
Usage Example:
const cleanedTerm = cleanSearchTerm(currentSearchTerm, currentLanguage);
const cached = getFromCache(cleanedTerm, 'summary');

if (cached) {
  // Use cached data immediately
  renderSummaryContent(cached, contentArea);
  return;
}

// Otherwise, fetch from API
fetchSummaryData(cleanedTerm);

Writing to Cache

The setCache() function stores data with automatic eviction:
content.js:179-185
function setCache(term, tab, data) {
  if (cache.size >= CACHE_SIZE) {
    const firstKey = cache.keys().next().value;
    cache.delete(firstKey);
  }
  cache.set(getCacheKey(term, tab), data);
}
Eviction Strategy:
  • FIFO (First In, First Out) - Oldest entry is removed first
  • Trigger: When cache reaches CACHE_SIZE limit
  • Deletion: Removes one entry to make room for new data
The FIFO strategy is simple and predictable. For most users, 30 entries is sufficient to cache recent searches without sophisticated LRU (Least Recently Used) logic.

Cache Integration

Every tab that fetches data follows this pattern:
// Example: fetchSummaryData
const cleanedTerm = cleanSearchTerm(searchTerm, currentLanguage);
const cacheKey = getCacheKey(cleanedTerm, 'summary');

// 1. Check cache first
if (cache.has(cacheKey)) {
  const contentArea = createTooltipShell(currentLanguage);
  renderSummaryContent(cache.get(cacheKey), contentArea);
  return;
}

// 2. Fetch from API
const response = await chrome.runtime.sendMessage({
  action: 'fetchWikipedia',
  term: cleanedTerm,
  language: currentLanguage
});

// 3. Store in cache
if (response.success) {
  setCache(cleanedTerm, 'summary', response.data);
}

Cache Invalidation

The cache is cleared in two scenarios:

1. Language Change

content.js:66-69
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'changeLanguage') {
    preferredLanguage = message.language;
    cache.clear();
  }
});

2. Manual Re-translation

content.js:1102-1106
retranslateBtn.addEventListener('click', () => {
  const cleanedTerm = cleanSearchTerm(currentSearchTerm, currentLanguage);
  cache.delete(getCacheKey(cleanedTerm, 'translate'));
  loadTranslateTab(contentArea);
});
The Summary, Define, and Facts tabs never invalidate their cache unless the language changes, as Wikipedia/Wikidata content is relatively stable.

Cache Performance

Benefits:
  • Instant tab switching - No loading spinners for cached tabs
  • Reduced API calls - Fewer requests to Wikipedia/Wiktionary/OpenAI
  • Lower latency - No network round-trip for cached data
  • Better UX - Smooth, responsive interface
Trade-offs:
  • Memory usage - ~30-150KB per browsing session
  • Stale data - Cache persists until page refresh or language change
  • No persistence - Cache is lost when page reloads

Cache Lifecycle

Debugging Cache Issues

To inspect the cache during development:
// In browser console (while on a page with the extension active)
console.log(cache);

// Check cache size
console.log(cache.size);

// View all cache keys
console.log([...cache.keys()]);

// Clear cache manually
cache.clear();
The cache is scoped to the content script instance, so each browser tab maintains its own independent cache.

Build docs developers (and LLMs) love