โ† Blog/Chrome Extension

Build a Chrome Extension to Highlight and Save Text from Any Webpage

Learn how to build a Chrome Extension that captures selected text from any webpage using the Selection API, saves it with chrome.storage.sync, and lets you copy or delete saved snippets.

๐Ÿ“… 2026-06-26โฑ 2 min read๐Ÿ“š Ebook #03

The Problem

You are reading an article and find an important quote or piece of information. You want to save it โ€” but where? Copy-paste into a notes app loses the source URL. Bookmarks save the page but not the specific text.

A Highlight & Save extension fixes this. Select any text, click the extension icon, and it's saved permanently with the source URL.

Content Scripts โ€” The Key Concept

Most Chrome Extensions only run in the popup. But to access the current webpage's content โ€” like selected text โ€” you need a content script: JavaScript that runs directly inside the web page.

// manifest.json
{
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["content.js"]
  }]
}

Capturing Selected Text

The window.getSelection() API returns the text the user has currently selected on the page:

// content.js โ€” runs inside the webpage
function getSelectedText() {
  const selection = window.getSelection();
  return selection ? selection.toString().trim() : '';
}

Message Passing

Content scripts and popups cannot communicate directly โ€” they need to send messages:

// popup.js โ€” ask the content script for selected text
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
  chrome.tabs.sendMessage(tabs[0].id, { action: 'getSelection' }, (response) => {
    if (response && response.text) {
      saveSnippet(response.text, tabs[0].url);
    }
  });
});

// content.js โ€” respond to the message
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'getSelection') {
    sendResponse({ text: getSelectedText() });
  }
});

Saving with chrome.storage.sync

chrome.storage.sync saves data to the user's Google account โ€” so snippets are available across all their Chrome instances:

function saveSnippet(text, url) {
  chrome.storage.sync.get(['snippets'], (result) => {
    const snippets = result.snippets || [];
    snippets.unshift({ text, url, date: new Date().toISOString() });
    chrome.storage.sync.set({ snippets });
  });
}

This is a preview. The full ebook includes the complete popup UI with delete functionality, copy to clipboard, truncating long text, and showing the source URL for each snippet.

Ready to Build This Yourself?

This article is a preview. The full ebook has complete code, detailed explanations, troubleshooting tips, and bonus sections โ€” all in a downloadable PDF.

Buy Full Ebook โ€” $1.50 in $YFIN
Pay with $YFIN on BNB Smart Chain ยท 30% burned permanently