Skip to main content

Overview

The Knowledge Tooltip extension integrates with the Wiktionary REST API to fetch detailed word definitions, etymologies, and usage examples. This powers the Dictionary tab in the tooltip.
Wiktionary provides linguistic information including parts of speech, definitions, etymologies, and usage notes. The extension supports both English and Arabic Wiktionary.

Features Using This API

  • Dictionary Tab: Displays word definitions and linguistic information
  • Multi-language Support: Switches between en.wiktionary.org and ar.wiktionary.org
  • Etymology & Usage: Shows word origins and example sentences

Definition Endpoint

Retrieves dictionary definitions for a word or term.

Endpoint

GET https://{domain}/api/rest_v1/page/definition/{term}
domain
string
required
Wiktionary domain: en.wiktionary.org or ar.wiktionary.org
term
string
required
URL-encoded word or term to look up (e.g., ephemeral, serendipity)

Implementation

From background.js:113-125:
async function fetchWiktionaryData(term, language) {
  const wikiDomain = language === 'ar' ? 'ar.wiktionary.org' : 'en.wiktionary.org';
  const url = `https://${wikiDomain}/api/rest_v1/page/definition/${encodeURIComponent(term)}`;

  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  return await response.json();
}

Request Example

chrome.runtime.sendMessage({
  action: 'fetchWiktionary',
  term: 'ephemeral',
  language: 'en'
}, (response) => {
  if (response.success) {
    console.log(response.data);
  } else {
    console.error(response.error);
  }
});

Response Structure

The API returns definitions organized by language and part of speech.
{language_code}
array
Array of definition groups for each language the word appears in

Response Example

{
  "en": [
    {
      "language": "English",
      "partOfSpeech": "adjective",
      "definitions": [
        {
          "definition": "Lasting for a short period of time.",
          "parsedExamples": [
            {
              "example": "The <b>ephemeral</b> nature of fashion trends."
            }
          ]
        },
        {
          "definition": "Existing for only one day, as with certain plants or insects."
        }
      ]
    },
    {
      "language": "English",
      "partOfSpeech": "noun",
      "definitions": [
        {
          "definition": "Something which lasts for a short period of time."
        }
      ]
    }
  ]
}

Multi-Language Definitions

Wiktionary entries often include definitions for the same word in multiple languages. For example, “chat” has entries in English, French, and other languages.

Example Multi-Language Response

Looking up “chat” in English Wiktionary:
{
  "en": [
    {
      "language": "English",
      "partOfSpeech": "noun",
      "definitions": [
        {
          "definition": "Informal conversation."
        }
      ]
    },
    {
      "language": "English",
      "partOfSpeech": "verb",
      "definitions": [
        {
          "definition": "To be engaged in informal conversation."
        }
      ]
    }
  ],
  "fr": [
    {
      "language": "French",
      "partOfSpeech": "noun",
      "definitions": [
        {
          "definition": "cat"
        }
      ]
    }
  ]
}

Parts of Speech

Wiktionary categorizes definitions by grammatical function:
Part of SpeechDescriptionExample
nounPerson, place, thing, or idea”The book is on the table”
verbAction or state of being”She runs every morning”
adjectiveDescribes a noun”The blue sky”
adverbDescribes a verb, adjective, or other adverb”He ran quickly
pronounReplaces a nounShe went home”
prepositionShows relationship between words”The cat is under the table”
conjunctionConnects words or clauses”Tea and coffee”
interjectionExpressive exclamationWow! That’s amazing”

Error Handling

Wiktionary may return 404 for words not in its database, especially for proper nouns, neologisms, or highly technical terms.

Error Flow

From background.js:36-40:
if (message.action === 'fetchWiktionary') {
  fetchWiktionaryData(message.term, message.language)
    .then(data => sendResponse({ success: true, data }))
    .catch(error => sendResponse({ success: false, error: toErrMsg(error) }));
  return true;
}

Common Error Scenarios

Status CodeReasonSolution
404Word not found in WiktionaryDisplay “No definition found” message
400Invalid term formatValidate input before sending
500Wiktionary server errorRetry or show error state

Fallback Strategy

The extension may implement a fallback to the Free Dictionary API when Wiktionary returns no results:
// From background.js:127-139 (Free Dictionary API fallback)
async function fetchFreeDictionaryData(term, language) {
  const langCode = language === 'ar' ? 'ar' : 'en';
  const url = `https://api.dictionaryapi.dev/api/v2/entries/${langCode}/${encodeURIComponent(term)}`;

  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  return await response.json();
}
The Free Dictionary API provides phonetics, audio pronunciations, and additional definition sources when Wiktionary data is unavailable.

Usage in Content Script

Example implementation for displaying Wiktionary definitions:
// Fetch Wiktionary definitions
chrome.runtime.sendMessage({
  action: 'fetchWiktionary',
  term: selectedWord,
  language: 'en'
}, (response) => {
  if (response.success && response.data) {
    const definitions = response.data;
    
    // Process each language section
    for (const langCode in definitions) {
      const langSections = definitions[langCode];
      
      langSections.forEach(section => {
        console.log(`${section.partOfSpeech}:`);
        section.definitions.forEach(def => {
          console.log(`  - ${def.definition}`);
        });
      });
    }
  } else {
    // Fallback to Free Dictionary API
    chrome.runtime.sendMessage({
      action: 'fetchFreeDictionary',
      term: selectedWord,
      language: 'en'
    });
  }
});

Rate Limits

Wiktionary REST API rate limits:
  • 200 requests/second for anonymous users
  • No authentication required
  • Same infrastructure as Wikipedia REST API

Best Practices

  1. Cache results: Store definitions locally to avoid repeat requests
  2. Debounce requests: Wait for user to finish typing before fetching
  3. User-Agent header: Identify your extension (handled automatically by Chrome)

Data Processing

Wiktionary definitions often include HTML markup. Process carefully:
// Strip HTML tags for plain text display
function stripHTML(html) {
  const tmp = document.createElement('div');
  tmp.innerHTML = html;
  return tmp.textContent || tmp.innerText || '';
}

// Or preserve formatting for rich display
function renderDefinition(htmlDefinition) {
  const container = document.createElement('div');
  container.innerHTML = htmlDefinition;
  return container;
}

Build docs developers (and LLMs) love