Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Security Model

Navigation, Content Security Policy and Permissions

Lock down what your Electron windows can load and open: block navigation, control new windows, set a strict Content Security Policy and deny unexpected permission requests.

Even with nodeIntegration off and the sandbox on, a window is only as safe as what it loads and what it is allowed to ask for. If a link in user content can navigate your main window to an attacker's site, or a popup can open with your preload attached, the isolation work is wasted. Electron gives you four levers for this: navigation events, the window-open handler, a Content Security Policy, and the permission handlers.

You will use all four in every serious app. Each is a small piece of code, and each is easy to test as a function that takes a URL or a permission name and returns allow or deny.

Controlling navigation

Your main window should show your app and nothing else. Intercept every navigation attempt:

JavaScript
win.webContents.on('will-navigate', (event, url) => {
  const target = new URL(url);
  if (target.origin !== 'file://' && target.origin !== 'https://app.example.com') {
    event.preventDefault();
    if (target.protocol === 'https:') shell.openExternal(url);
  }
});

will-navigate fires for user clicks and for location.href = .... It does not fire for the initial loadURL, and it does not cover redirects, for which there is will-redirect. Treat all three the same way.

Controlling new windows

Links with target="_blank" and window.open create new windows. Use setWindowOpenHandler to decide each time:

JavaScript
win.webContents.setWindowOpenHandler(({ url }) => {
  if (url.startsWith('https://')) shell.openExternal(url);
  return { action: 'deny' };
});

Returning { action: 'deny' } blocks the new window; the handler itself can still send the URL to the user's browser. Only return allow for windows you want, and do it with explicit options, for instance a small settings popup. A popup that inherits your preload and a loose origin is a privilege-escalation path.

An origin policy you can test

Both handlers reduce to one question: is this URL allowed to load in-app, open externally, or be dropped? Put the answer in a pure function and unit-test it.

Node.js A navigation policy function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The fourth line is the classic trap: app.example.com.evil.example begins with the right text but has a different origin. Always compare parsed origins, never string prefixes.

Content Security Policy

A CSP is an HTTP header (or <meta> tag) that tells the renderer which sources of scripts, styles, images and connections are allowed. It is your safety net against injected script: even if an attacker gets markup into the page, a strict policy refuses to execute inline script and refuses to load code from unknown hosts.

For an Electron app that loads local files, a good starting policy is:

HTML
<meta http-equiv="Content-Security-Policy"
  content="default-src 'self';
           script-src 'self';
           style-src 'self' 'unsafe-inline';
           img-src 'self' data:;
           connect-src 'self' https://api.example.com;
           object-src 'none';
           base-uri 'none';
           frame-ancestors 'none'">

What it says: load everything from the app itself, allow no inline or eval scripts (there is no 'unsafe-inline' or 'unsafe-eval' under script-src), allow images from the app or data: URLs, allow network calls only to your API, and forbid plugins. Developer servers like Vite inject inline scripts and need a looser policy in development only; ship the strict one in production.

If your content comes from a server you can set the header for all responses with the session:

JavaScript
import { session } from 'electron';

session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
  callback({
    responseHeaders: {
      ...details.responseHeaders,
      'Content-Security-Policy': ["default-src 'self'; script-src 'self'"],
    },
  });
});

Checking a policy

A CSP is easy to weaken by accident. This lints a policy string for the usual mistakes.

Node.js A CSP linter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Permissions

Pages can ask for the camera, microphone, geolocation, notifications, screen capture and more. Electron's default is to grant most of them, which is the opposite of what a browser does. Take control with a handler on the session:

JavaScript
const ALLOWED = new Set(['notifications']);

session.defaultSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
  const fromApp = new URL(details.requestingUrl).origin === 'https://app.example.com';
  callback(fromApp && ALLOWED.has(permission));
});

session.defaultSession.setPermissionCheckHandler((wc, permission, origin) =>
  origin === 'https://app.example.com' && ALLOWED.has(permission));

Write it as deny by default. Add a permission when you ship a feature that needs it, and check the requesting URL so an iframe from another origin cannot borrow it. The request handler covers asking; the check handler covers synchronous queries like navigator.permissions.query, so set both.

flowchart TD
  A["Page asks for camera"] --> B{"Request handler"}
  B -- "app origin and in allowlist" --> C["Granted"]
  B -- "anything else" --> D["Denied"]

Deny by default: a feature must be named in the allowlist to work.

Putting it together

For each window you create, do these in order: set the preload and safe webPreferences, install will-navigate and will-redirect guards, install setWindowOpenHandler, make sure the page ships a CSP, and set the permission handlers once on the session. Then test each rule as plain functions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why compare URL origins instead of checking url.startsWith('https://app.example.com')?

    Prefix tests are fooled by lookalike hosts. Parse the URL and compare the whole origin.
  2. 2. What does returning { action: 'deny' } from setWindowOpenHandler do?

    The popup is not created. You can still hand the URL to shell.openExternal if it is safe.
  3. 3. Which CSP directive weakens script protection the most?

    'unsafe-inline' lets injected inline scripts run, which defeats the main purpose of a CSP.
  4. 4. Electron's default for permission requests like camera is to

    Unlike a browser, Electron grants by default. Install setPermissionRequestHandler and setPermissionCheckHandler and deny by default.

Summary

  • Guard will-navigate, will-redirect and setWindowOpenHandler; never let your main window leave your own origin.
  • Decide URLs by parsed origin, not by string prefix.
  • Ship a strict CSP: no inline scripts, no eval, only the hosts you need.
  • Install both permission handlers and deny by default, checking the requesting origin.
  • Express rules as pure functions so they can be unit-tested.

Next: Validating IPC and Handling Secrets