Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Permissions and Security

Secure Messaging and Untrusted Input

Treat web pages as hostile, validate message senders and shapes, avoid innerHTML and XSS in content scripts, limit externally_connectable, and apply a practical security checklist to your extension.

A content script lives in a web page, and a web page can be written by anyone. The moment your extension reads text from a page, accepts a message, or inserts HTML, you are at a trust boundary. Extensions have powerful permissions, so a bug that lets a hostile page steer them is serious: that is how malicious sites steal data through a careless extension. This lesson is a practical security guide.

Know your trust levels

flowchart LR
    W["Web page<br/>(untrusted)"] --> C["Content script<br/>(semi-trusted)"]
    C --> S["Service worker<br/>(trusted, has permissions)"]
    P["Popup / options<br/>(trusted)"] --> S

Data moving to the right gains power. Never let untrusted data decide what a trusted part does.

  • Web pages are untrusted. They can change the DOM your content script reads, fake events and even post messages.
  • Content scripts run next to the page. Treat what they send as untrusted input too: a compromised page can influence them.
  • Service worker and extension pages have the permissions. Everything they receive must be validated.

Validate the sender and the shape

Any message that reaches your service worker came from some context. Check sender, then check the message.

JavaScript
// service-worker.js (real extension code)
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // 1. Only our own extension may talk to us
  if (sender.id !== chrome.runtime.id) return;

  // 2. Only content scripts in tabs may send this type
  if (message?.type === "save-note") {
    if (!sender.tab) return;
    // 3. Validate the shape and limits
    if (typeof message.text !== "string" || message.text.length > 2000) return;
    saveNote(message.text);
  }
});

Do not trust any field that tells the worker what to do with a privilege, for example message.url passed straight into chrome.tabs.create, or message.selector used to pick which cookie to read. Instead map a small allowed set of actions.

A message validator

A small map of allowed message types, each with its own validator, gives you an allow-list instead of "trust whatever arrives".

Never turn page text into HTML

The most common extension vulnerability is DOM-based XSS: reading text from a page (a title, a username, a comment) and inserting it with innerHTML.

JavaScript
// Dangerous: the page controls item.title
list.innerHTML += `<li>${item.title}</li>`;

If item.title is <img src=x onerror=...>, the markup becomes live. In an extension page, the CSP blocks inline handlers, but you still must not rely on it, and in a content script the injected markup lives inside the page itself.

The safe way is textContent, or building elements:

JavaScript
const li = document.createElement("li");
li.textContent = item.title;     // text, never parsed as HTML
list.append(li);
textContent versus innerHTML

If you must show rich text, sanitize it with a well-reviewed library (packaged with the extension) and allow only a short list of tags; never write your own regex filter.

Be careful with window.postMessage

Pages and content scripts can talk through window.postMessage. Any script on the page can post too, so a content script that reacts to those messages must check event.source === window and event.origin, and must validate the payload. Prefer extension messaging (runtime.sendMessage) between your own parts, and use postMessage only when a page script really needs to talk to you.

externally_connectable

By default, only your extension talks to itself. If a website should message your extension (for example, your own web app), declare it and keep the list tiny:

JSON
{
  "externally_connectable": {
    "matches": ["https://app.example.com/*"]
  }
}

The worker then receives runtime.onMessageExternal, and sender.origin tells you who called. Never use a broad pattern, and treat every external message as untrusted input.

Other habits that keep you safe

  • No remote code, no eval, as covered in Content Security Policy.
  • Use HTTPS for every request. Do not send user data to third parties unless you declare it.
  • Do not store secrets (API keys, tokens) in the extension: anyone can unzip it. Keep them on your server and have the server check the user.
  • Pin and audit dependencies; bundle them and remove what you do not use.
  • Limit web_accessible_resources to what pages truly need, and narrow its matches; every listed file can be probed by any matching website.
  • Fail closed: when validation fails, do nothing and log.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A message asks the service worker to open any URL given in message.url. What is the safest design?

    Never let untrusted data choose a privileged action or target. Map allowed actions to code you control.
  2. 2. Which line is safe for inserting a page's title into a list item?

    textContent treats the value as plain text. The others parse it as HTML.
  3. 3. What does sender.id !== chrome.runtime.id check do in onMessage?

    sender.id is the sending extension's id. Comparing it with your own id stops other extensions' messages.
  4. 4. Where should an API secret for your backend be stored?

    Extension packages can be unzipped by anyone, so a secret in it is public.

Summary

  • Treat pages and content scripts as untrusted; validate sender and shape in the service worker.
  • Use an allow-list of message types and never let input pick privileged targets.
  • Use textContent or sanitized HTML, never raw innerHTML with page data.
  • Keep externally_connectable and web_accessible_resources minimal; keep secrets on the server.

Next: Least Privilege, Privacy and Data Handling