Building a Chrome Side Panel AI Assistant: Permissions, Content Extraction, and Streaming Output
When reading long articles, users often need to look up unfamiliar terms, which usually means copying text, switching to a search engine, and jumping back. An AI assistant built into the browser side panel eliminates this context switching. This article walks through building one with a Chrome extension (Manifest V3), covering permission configuration, page content extraction, message passing, streaming output, and common troubleshooting. Other browsers have similar extension systems, but API names and permission details may differ, so consult the relevant documentation before implementing.
Building a Chrome Side Panel AI Assistant: Permissions, Content Extraction, and Streaming Output
When reading a long article and looking up an unfamiliar concept, users typically copy the text, open a search engine, and switch back to the original page. An AI assistant in the browser side panel removes these steps. Three questions come up most often among developers: how to integrate the assistant, which permissions are required, and how to avoid disrupting the reading experience. This article uses a Chrome extension (Manifest V3) as an example and covers permission configuration, content extraction, message channels, streaming rendering, and common errors. Other browsers’ extension systems are similar, though API names and permission details vary—check the corresponding documentation before implementing.
1. Define What the Side Panel Solves
The value of a side panel assistant is that users stay on the current page. They click the extension icon, the panel opens, and the page position remains unchanged, so they can ask questions immediately. This interaction reduces tab switching, but it depends on two things: the page’s main content must be extracted accurately, and users must understand which content will be sent to the model. The second point drives most of the security design discussed below.
2. Requesting Minimal Permissions
The side panel requires the sidePanel permission. Reading page content requires scripting. The activeTab permission only grants temporary access to the current tab after the user explicitly triggers the extension (clicking the icon or a context menu item). Compared with listing <all_urls> in host_permissions, this approach carries far less risk.
{"manifest_version": 3,"name": "Page Assistant Example","version": "1.0.0","permissions": ["sidePanel", "activeTab", "scripting", "storage"],"host_permissions": ["https://llm-proxy.example.com/*"],"background": { "service_worker": "background.js" },"side_panel": { "default_path": "panel.html" },"action": { "default_title": "Open Page Assistant" }}
Never put the model’s API key in extension code, because extension packages can be unpacked and read. Declare only your own backend proxy’s domain in host_permissions; the proxy forwards requests and keeps the key safe.
3. Extracting the Main Content
Functions injected via chrome.scripting.executeScript are serialized before execution in the page, so they cannot reference external variables and must be self-contained.
// Injected via chrome.scripting.executeScript; the function body must be self-containedfunction extractMainContent() {// Skip pages containing password fields (login, payment) entirelyif (document.querySelector('input[type="password"]')) {return { skipped: true, reason: 'SENSITIVE_PAGE' };}const root = document.querySelector('article, main, [role="main"]') || document.body;const clone = root.cloneNode(true);clone.querySelectorAll('script, style, noscript, iframe, nav, aside, footer, form, [aria-hidden="true"]').forEach((el) => el.remove());const text = (clone.textContent || '').replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim();return {skipped: false,title: document.title,url: location.href,text: text.slice(0, 20000),};}
Different pages call for different extraction strategies. The table below summarizes the options:
| Strategy | Best for | Pros | Main risk | Fallback on failure |
|---|---|---|---|---|
| Semantic tag selection (article, main) | News, blogs, documentation sites | Simple and fast | May pick up navigation on non-standard pages | Fall back to body and strip navigation and sidebars |
| Readability-style library | Long, complex articles | Higher accuracy in detecting main content | Larger bundle; performs poorly on app-like pages | Fall back to semantic tag selection |
| DOM pruning rules | Fixed sites with stable templates | Controllable, can be tuned per site | Rules break when the site is redesigned | Fall back to generic rules |
| Sliding window or Map-Reduce | Very long text | Stays within the context window | More calls and higher latency; details may be lost | Truncate to the first few paragraphs and inform the user |
A Readability-style library can be bundled with the extension and loaded via the files parameter at injection time. Single-page applications may not have finished rendering the content when the script runs, resulting in empty extraction. In that case, use a MutationObserver to wait for the content to stabilize, then retry once.
4. Connecting the Side Panel to the Background
Let the background service worker handle tab queries and script injection uniformly; the side panel only sends requests via runtime.sendMessage. Centralizing error codes in one place makes debugging easier.
// background.jschrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {if (msg.type !== 'EXTRACT_PAGE') return false;(async () => {try {const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });if (!tab?.id || !/^https?:\/\//.test(tab.url ?? '')) {throw new Error('UNSUPPORTED_PAGE');}const [injection] = await chrome.scripting.executeScript({target: { tabId: tab.id },func: extractMainContent, // same function as defined above});const page = injection?.result;if (!page) throw new Error('EMPTY_RESULT');if (page.skipped) throw new Error(page.reason);sendResponse({ ok: true, page });} catch (err) {sendResponse({ ok: false, error: err.message });}})();return true; // Keep the message channel open for the async response});
The side panel’s script must live in a separate panel.js file. The default content security policy (CSP) for extension pages forbids inline scripts, so onclick handlers written directly in HTML will not run.
// panel.jschrome.runtime.sendMessage({ type: 'EXTRACT_PAGE' }, (resp) => {if (!resp?.ok) {showError(resp?.error ?? 'UNKNOWN');return;}setPageContext(resp.page);});
5. Streaming the Response
There are two common streaming approaches. SSE is HTTP-based, has a simple protocol, and works well with proxies and load balancers—but the native EventSource API only supports GET, while submitting questions usually requires POST to carry page content. WebSocket is a bidirectional channel suited to scenarios that frequently exchange control signals. For a Q&A assistant, interruption can be handled by closing the HTTP stream with AbortController, so WebSocket is usually unnecessary. The recommended approach is to read the stream with fetch and parse the SSE format.
async function streamAnswer(messages, onDelta, signal) {const res = await fetch('https://llm-proxy.example.com/v1/chat', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ stream: true, messages }),signal,});if (!res.ok) throw new Error(`HTTP_${res.status}`);const reader = res.body.getReader();const decoder = new TextDecoder();let buffer = '';while (true) {const { done, value } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });const lines = buffer.split('\n');buffer = lines.pop(); // The last line may be incomplete; keep it for the next batchfor (const line of lines) {if (!line.startsWith('data: ')) continue;const data = line.slice(6).trim();if (data === '[DONE]') return;const delta = JSON.parse(data).choices?.[0]?.delta?.content ?? '';if (delta) onDelta(delta);}}}
Handle these edge cases in your implementation:
- Time to first byte: If no data arrives within 15 seconds, call
abort()and prompt the user to retry. - Total duration limit: For example, 120 seconds; on timeout, keep whatever has already been output.
- User interruption: The stop button calls
controller.abort(); catchAbortErrorand mark the response as “interrupted” in the UI. - Reconnection after a dropped stream: Text already generated by the model generally cannot be resumed mid-stream. After a disconnect, keep the existing output and let the user click “regenerate” manually. Do not automatically append output from a new request—this easily produces duplicates or broken sentences.
- Rendering: Append incremental content with
textContent, neverinnerHTML. This prevents HTML in the model output or page text from being executed as code.
6. Controlling Context Length and Privacy Risks
When the page content exceeds the model’s context window, truncate it or process it in chunks. Roughly speaking, English text consumes about 1 token per word depending on the tokenizer—always rely on actual token counts.
Page content is sent to the model service and may contain personal information, internal documents, or credentials. Recommended measures:
- Minimal permissions: Use only
activeTab; do not request site-wide read access. - Explicit user consent: Explain on first use that page content will be sent, and enable the feature only after the user confirms.
- Exclude sensitive pages: Skip pages with password fields by default, as well as banking, payment, and corporate intranet domains.
- Redact before sending: Replace email addresses, phone numbers, and ID numbers. The regex below only covers common formats and is not exhaustive.
- Logging policy: Never log page content; keep only request IDs, length, duration, and error codes, and set a retention period.
- Compliance review: Explain your data handling to users and check it against the personal data protection regulations applicable in your region.
function redact(text) {return text.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g, '[EMAIL]').replace(/1[3-9]\d{9}/g, '[PHONE]').replace(/\d{17}[\dXx]/g, '[ID_NUMBER]');}
7. Common Errors and Troubleshooting
| Symptom | Likely cause | How to investigate |
|---|---|---|
executeScript throws a permission error |
scripting not declared, or the call is not triggered by a user action |
Check the manifest’s permissions; confirm injection happens after a user action |
Returns UNSUPPORTED_PAGE |
The current page is a chrome:// page, a web store page, or otherwise non-injectable | Ask the user to switch to a regular web page; do not retry |
| Extraction result is empty | SPA hasn’t rendered the content when the script runs | Use a MutationObserver to wait for the content to stabilize and retry once; if still empty, ask the user to refresh |
| Main content is mixed with navigation or comments | Page lacks semantic tags; selection scope too broad | Add DOM pruning rules for that site, or switch to Readability |
| CORS or network errors when calling the model | Proxy domain missing from host_permissions, or proxy not allowing the extension origin |
Add the domain to host_permissions and configure a CORS allowlist on the proxy |
| Panel button clicks do nothing | Inline event handlers blocked by the extension page’s CSP | Move scripts to external files and bind events with addEventListener |
| Streaming output stops mid-response | Network interruption, proxy timeout, or backend restart | Keep the existing output, show an interruption marker, and offer a regenerate button |
| Duplicates or broken sentences in answers | Frontend automatically appended output from a new request after a disconnect | Never auto-resume after a disconnect; only allow manual regeneration |
