Creating a Chrome extension that summarizes all the text on any webpage you're viewing involves several steps. Below is a complete "soup to nuts" codebase for a basic Chrome extension that:
- Injects content script into the current tab.
- Extracts visible text from the page.
- Sends it to a summarization function (local or via an API).
- Displays the summary in a popup.
🧱 Project Structure
summarizer-extension/
│
├── manifest.json
├── popup.html
├── popup.js
├── content.js
├── background.js
└── icon.png (optional)
1. manifest.json
{
"manifest_version": 3,
"name": "Page Text Summarizer",
"version": "1.0",
"description": "Summarizes all visible text on the current page.",
"permissions": ["activeTab", "scripting"],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_icon": "icon.png"
},
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"host_permissions": ["<all_urls>"]
}
2. popup.html
<!DOCTYPE html>
<html>
<head>
<style>
body {
width: 300px;
padding: 10px;
font-family: sans-serif;
font-size: 14px;
}
#summary {
margin-top: 10px;
white-space: pre-wrap;
word-wrap: break-word;
}
</style>
</head>
<body>
<h3>Page Summary</h3>
<button id="summarizeBtn">Summarize Page</button>
<div id="summary">Click the button above.</div>
<script src="popup.js"></script>
</body>
</html>
3. popup.js
document.getElementById('summarizeBtn').addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: getPageText
}, (results) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
return;
}
const textContent = results[0].result;
// Local summarization (basic)
const summary = summarizeText(textContent);
document.getElementById('summary').textContent = summary || "No text found.";
});
});
});
// This function is called in the context of the page
function getPageText() {
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
let text = '';
while (walker.nextNode()) {
const node = walker.currentNode;
const parent = node.parentNode;
if (window.getComputedStyle(parent).visibility !== 'hidden' &&
window.getComputedStyle(parent).display !== 'none') {
text += node.textContent + ' ';
}
}
return text.trim();
}
// Basic local summarizer (you can replace this with an API call)
function summarizeText(text, sentenceCount = 3) {
if (!text) return '';
const sentences = text.split(/(?<=[.!?])\s+/);
if (sentences.length <= sentenceCount) return sentences.join(' ');
// Very naive approach: take first few sentences
return sentences.slice(0, sentenceCount).join(' ') + '...';
}
4. content.js (Optional)
This file isn't used directly here since we use executeScript and define getPageText() inline. You can leave this blank or remove it from manifest.json.
5. background.js (Optional)
If you don’t need long-running logic or event handling, this file can be empty or removed.
// Optional background logic
chrome.runtime.onInstalled.addListener(() => {
console.log("Summarizer Extension Installed");
});
✅ How to Load the Extension in Chrome
- Go to
chrome://extensions/.
- Enable Developer Mode (toggle top-right).
- Click "Load unpacked".
- Select the folder containing your extension files.
🔁 Optional Enhancements
A. Use an AI API for Better Summarization (e.g., Hugging Face, OpenAI)
Replace the summarizeText function with a fetch to an API like:
async function summarizeWithAPI(text) {
const response = await fetch('https://api-inference.huggingface.co/models/facebook/bart-large-cnn', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_HUGGINGFACE_TOKEN',
'Content-Type': 'application/json'
},
body: JSON.stringify({ inputs: text })
});
const data = await response.json();
return data[0]?.summary_text || "Summary unavailable.";
}
You'd need to handle cross-origin requests and security policies properly (via a backend proxy or CORS-unblocking extension).
📦 Final Notes
- This extension works best on standard HTML pages with readable text.
- For SPAs or dynamically loaded content, you may need to wait for DOM updates.
- Be mindful of performance and privacy when sending text to external APIs.
Would you like me to package this into a downloadable ZIP or add support for a specific summarization model?