To create a Chrome extension that reads the selected word on a website and provides multiple one-word meanings of the word separated by semicolons, you can follow the steps below. This extension will detect when a user selects a word on any webpage, fetch synonyms (one-word meanings) using an external API, and display them in a tooltip near the selected word.
Overview
- Create the extension's manifest file (
manifest.json).
- Write a content script (
content.js) to detect text selection and fetch meanings.
- Use a dictionary or synonym API to get the meanings.
- Display the meanings to the user in a tooltip.
- Load and test the extension in Chrome.
Let's go through each step in detail.
Step 1: Create the Manifest File (manifest.json)
The manifest.json file tells Chrome about your extension, what permissions it needs, and which scripts to load.
Create a new directory for your Chrome extension files, and inside that directory, create a file named manifest.json with the following content:
{
"manifest_version": 3,
"name": "Word Meaning Finder",
"version": "1.0",
"description": "Reads the selected word and provides multiple one-word meanings.",
"permissions": ["scripting", "activeTab"],
"host_permissions": ["https://api.datamuse.com/"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
Explanation:
manifest_version: Specifies the version of the manifest file format—use 3 for the latest version.
name, version, description: Basic information about your extension.
permissions: Permissions required by the extension.
"scripting": Allows injection of scripts into web pages.
"activeTab": Grants access to the currently active tab when the user interacts with the extension.
host_permissions: Permissions to access specific hosts—in this case, the Datamuse API.
content_scripts: Scripts that are injected into web pages.
matches: Specifies which pages the content script should run on. "<all_urls>" means all pages.
js: The JavaScript files to inject.
Step 2: Write the Content Script (content.js)
Create a file named content.js in the same directory with the following content:
// content.js
// Listen for mouseup events (when the user finishes selecting text)
document.addEventListener('mouseup', function (e) {
let selectedText = window.getSelection().toString().trim();
// Check if the selected text is a single word
if (selectedText && !/\s/.test(selectedText)) {
// Remove any existing tooltip
removeExistingTooltip();
// Fetch meanings of the selected word
fetchMeanings(selectedText, e.pageX, e.pageY);
} else {
// Remove existing tooltip if any
removeExistingTooltip();
}
});
// Remove tooltip on mousedown (when the user starts a new selection)
document.addEventListener('mousedown', function () {
removeExistingTooltip();
});
// Function to fetch meanings from the Datamuse API
function fetchMeanings(word, x, y) {
fetch(`https://api.datamuse.com/words?ml=${word}&max=5`)
.then(response => response.json())
.then(data => {
let meanings = data.map(obj => obj.word);
if (meanings.length > 0) {
showTooltip(x, y, meanings.join('; '));
}
})
.catch(error => {
console.error('Error fetching meanings:', error);
});
}
// Function to display a tooltip near the selected word
function showTooltip(x, y, text) {
let tooltip = document.createElement('div');
tooltip.id = 'word-meaning-tooltip';
tooltip.innerText = text;
// Style the tooltip
Object.assign(tooltip.style, {
position: 'absolute',
top: (y + 10) + 'px',
left: (x + 10) + 'px',
backgroundColor: '#fffbea',
border: '1px solid #ccc',
padding: '5px',
zIndex: 10000,
boxShadow: '2px 2px 6px rgba(0,0,0,0.2)',
borderRadius: '4px',
fontSize: '14px',
color: '#333',
maxWidth: '300px',
wordWrap: 'break-word'
});
document.body.appendChild(tooltip);
}
// Function to remove existing tooltip
function removeExistingTooltip() {
let existingTooltip = document.getElementById('word-meaning-tooltip');
if (existingTooltip) {
existingTooltip.remove();
}
}
Explanation:
- Event Listeners:
mouseup: Triggered when the user finishes selecting text. Checks if a single word is selected and fetches meanings.
mousedown: Triggered when the user starts a new selection or clicks elsewhere. Removes any existing tooltip.
- Functions:
fetchMeanings(): Makes an API call to the Datamuse API to get words with similar meanings.
showTooltip(): Creates and styles a tooltip to display the meanings near the mouse position.
removeExistingTooltip(): Removes the tooltip from the page if it exists.
- API Used: Datamuse API, which provides words related to a given word (we use
ml parameter for "means like").
Step 3: Use an External API to Get Meanings
In this example, we use the Datamuse API to fetch words that have similar meanings to the selected word.
- API Endpoint:
https://api.datamuse.com/words
- Parameters:
ml: Means like (words with similar meaning).
max: Maximum number of results (set to 5 in the script).
- Example Request:
https://api.datamuse.com/words?ml=example&max=5
The API returns a JSON array of word objects, where each object contains a word property.
The content script processes this response to extract the words and display them to the user.
Step 4: Display the Meanings to the User
The showTooltip() function creates a tooltip element (<div>) and positions it near the mouse cursor using the pageX and pageY coordinates from the mouse event.
Styling the Tooltip:
The tooltip is styled directly in the script using JavaScript to set CSS properties, including:
position: 'absolute': Positions the tooltip relative to the document.
top and left: Positions the tooltip near the cursor, offset slightly for better visibility.
backgroundColor, border, padding, borderRadius: Styles to make the tooltip visually appealing.
zIndex: Ensures the tooltip appears above other elements on the page.
maxWidth, wordWrap: Ensures the tooltip content wraps appropriately.
Step 5: Load and Test the Extension in Chrome
-
Open Chrome and go to chrome://extensions.
-
Enable "Developer mode" by toggling the switch in the top-right corner.
-
Click "Load unpacked" and select the directory containing your extension files (manifest.json and content.js).
-
Test the extension:
- Navigate to any webpage.
- Select a single word by clicking and dragging your mouse over it.
- Release the mouse button.
- A tooltip should appear near your cursor displaying multiple one-word meanings of the selected word, separated by semicolons.
Additional Notes
-
Single Word Selection: The script checks that the selected text is a single word (no spaces) using the regular expression !/\s/.test(selectedText). This ensures only individual words are processed.
-
Error Handling: The fetch() call includes a .catch() to log any errors that occur during the API request.
-
Clean-up: Tooltips are removed when the user starts a new selection (mousedown event) or selects non-word text.
-
Permission Considerations:
host_permissions: With Manifest V3, you need to specify host_permissions separately to access external URLs (like the Datamuse API).
scripting Permission: Allows the extension to use the chrome.scripting API, though in this simple extension we are not utilizing it directly.
-
Security Considerations: Be cautious when injecting elements into web pages to avoid conflicts with page scripts or styles.
Customizations
Troubleshooting
Conclusion
By following the steps above, you've created a simple Chrome extension that enhances your browsing experience by providing quick access to word meanings directly on any webpage. This extension leverages web technologies (JavaScript, HTML, CSS) and external APIs to interact with web content dynamically.
Feel free to expand upon this foundation by adding features such as:
- Definitions in addition to synonyms.
- Support for multiple languages.
- Options page to customize behavior (e.g., number of meanings, display settings).
- Keyboard shortcuts to trigger the lookup.
Always ensure that you respect the terms of service of any APIs you use and handle user data responsibly.