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.

    1. {
    2. "manifest_version": 3,
    3. "name": "Page Assistant Example",
    4. "version": "1.0.0",
    5. "permissions": ["sidePanel", "activeTab", "scripting", "storage"],
    6. "host_permissions": ["https://llm-proxy.example.com/*"],
    7. "background": { "service_worker": "background.js" },
    8. "side_panel": { "default_path": "panel.html" },
    9. "action": { "default_title": "Open Page Assistant" }
    10. }

    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.

    1. // Injected via chrome.scripting.executeScript; the function body must be self-contained
    2. function extractMainContent() {
    3. // Skip pages containing password fields (login, payment) entirely
    4. if (document.querySelector('input[type="password"]')) {
    5. return { skipped: true, reason: 'SENSITIVE_PAGE' };
    6. }
    7. const root = document.querySelector('article, main, [role="main"]') || document.body;
    8. const clone = root.cloneNode(true);
    9. clone.querySelectorAll(
    10. 'script, style, noscript, iframe, nav, aside, footer, form, [aria-hidden="true"]'
    11. ).forEach((el) => el.remove());
    12. const text = (clone.textContent || '')
    13. .replace(/[ \t]+/g, ' ')
    14. .replace(/\n{3,}/g, '\n\n')
    15. .trim();
    16. return {
    17. skipped: false,
    18. title: document.title,
    19. url: location.href,
    20. text: text.slice(0, 20000),
    21. };
    22. }

    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.

    1. // background.js
    2. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
    3. chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    4. if (msg.type !== 'EXTRACT_PAGE') return false;
    5. (async () => {
    6. try {
    7. const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
    8. if (!tab?.id || !/^https?:\/\//.test(tab.url ?? '')) {
    9. throw new Error('UNSUPPORTED_PAGE');
    10. }
    11. const [injection] = await chrome.scripting.executeScript({
    12. target: { tabId: tab.id },
    13. func: extractMainContent, // same function as defined above
    14. });
    15. const page = injection?.result;
    16. if (!page) throw new Error('EMPTY_RESULT');
    17. if (page.skipped) throw new Error(page.reason);
    18. sendResponse({ ok: true, page });
    19. } catch (err) {
    20. sendResponse({ ok: false, error: err.message });
    21. }
    22. })();
    23. return true; // Keep the message channel open for the async response
    24. });

    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.

    1. // panel.js
    2. chrome.runtime.sendMessage({ type: 'EXTRACT_PAGE' }, (resp) => {
    3. if (!resp?.ok) {
    4. showError(resp?.error ?? 'UNKNOWN');
    5. return;
    6. }
    7. setPageContext(resp.page);
    8. });

    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.

    1. async function streamAnswer(messages, onDelta, signal) {
    2. const res = await fetch('https://llm-proxy.example.com/v1/chat', {
    3. method: 'POST',
    4. headers: { 'Content-Type': 'application/json' },
    5. body: JSON.stringify({ stream: true, messages }),
    6. signal,
    7. });
    8. if (!res.ok) throw new Error(`HTTP_${res.status}`);
    9. const reader = res.body.getReader();
    10. const decoder = new TextDecoder();
    11. let buffer = '';
    12. while (true) {
    13. const { done, value } = await reader.read();
    14. if (done) break;
    15. buffer += decoder.decode(value, { stream: true });
    16. const lines = buffer.split('\n');
    17. buffer = lines.pop(); // The last line may be incomplete; keep it for the next batch
    18. for (const line of lines) {
    19. if (!line.startsWith('data: ')) continue;
    20. const data = line.slice(6).trim();
    21. if (data === '[DONE]') return;
    22. const delta = JSON.parse(data).choices?.[0]?.delta?.content ?? '';
    23. if (delta) onDelta(delta);
    24. }
    25. }
    26. }

    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(); catch AbortError and 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, never innerHTML. 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:

    1. Minimal permissions: Use only activeTab; do not request site-wide read access.
    2. Explicit user consent: Explain on first use that page content will be sent, and enable the feature only after the user confirms.
    3. Exclude sensitive pages: Skip pages with password fields by default, as well as banking, payment, and corporate intranet domains.
    4. Redact before sending: Replace email addresses, phone numbers, and ID numbers. The regex below only covers common formats and is not exhaustive.
    5. Logging policy: Never log page content; keep only request IDs, length, duration, and error codes, and set a retention period.
    6. Compliance review: Explain your data handling to users and check it against the personal data protection regulations applicable in your region.
    1. function redact(text) {
    2. return text
    3. .replace(/[\w.+-]+@[\w-]+\.[\w.]+/g, '[EMAIL]')
    4. .replace(/1[3-9]\d{9}/g, '[PHONE]')
    5. .replace(/\d{17}[\dXx]/g, '[ID_NUMBER]');
    6. }

    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