Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Main and Renderer Processes

Loading Content, Navigation and Custom Protocols

Load pages in Electron with loadFile and loadURL, control navigation and new windows, open links in the default browser, and serve app files through a custom protocol.

A window is useless until it shows something. Electron gives you several ways to load content, and just as importantly, ways to restrict where a window can go afterwards. Users click links; pages call window.open; a bug can redirect the window to a remote site. Deciding what is allowed is part of building a safe app.

loadFile and loadURL

JavaScript
// Local file inside your app (production)
win.loadFile(path.join(__dirname, '../renderer/index.html'))

// Same file with a query string or hash
win.loadFile('index.html', { query: { page: 'settings' }, hash: 'top' })

// Dev server (development with Vite or webpack)
win.loadURL('http://localhost:5173')

// A remote page (be careful, see the security chapter)
win.loadURL('https://example.com')

loadFile converts a path to a file:// URL for you. loadURL accepts any URL: http, https, file, or a custom protocol. Both return promises that resolve when the load finishes and reject if it fails, so you can write:

JavaScript
try {
  await win.loadFile('index.html')
} catch (error) {
  console.error('Failed to load page', error)
}

A common pattern chooses the source by environment:

JavaScript
const devServerUrl = process.env.VITE_DEV_SERVER_URL

if (devServerUrl && !app.isPackaged) {
  win.loadURL(devServerUrl)
} else {
  win.loadFile(path.join(__dirname, '../renderer/index.html'))
}

Load events

Listen on win.webContents to react to progress:

Event Meaning
did-start-loading A load began (show a spinner)
dom-ready The DOM of the main frame is ready
did-finish-load Everything finished loading
did-fail-load A load failed (offline, wrong path, blocked)
did-navigate The main frame navigated to a new URL
did-navigate-in-page A hash or history.pushState change (single-page apps)
JavaScript
win.webContents.on('did-fail-load', (event, code, description, url) => {
  console.error(`Could not load ${url}: ${description} (${code})`)
  win.loadFile('error.html')
})

Controlling navigation

By default a page can navigate itself anywhere. For example a link <a href="https://evil.example"> navigates the app window to that site, and the site then runs inside your app. Two events let you decide:

  • will-navigate: fires before the window navigates to a new URL (not for in-page hash changes). Call event.preventDefault() to cancel.
  • setWindowOpenHandler: decides what happens when the page opens a new window (window.open, target="_blank").
JavaScript
const { shell } = require('electron')

win.webContents.on('will-navigate', (event, url) => {
  const allowed = new URL(url).origin === 'file://' // our own pages only
  if (!allowed) {
    event.preventDefault()
    if (url.startsWith('https://')) shell.openExternal(url)   // use the user's browser
  }
})

win.webContents.setWindowOpenHandler(({ url }) => {
  if (url.startsWith('https://')) shell.openExternal(url)
  return { action: 'deny' }                                   // never create an app window for it
})

shell.openExternal opens a URL in the user's default browser or handler app. Only pass URLs you have validated: allow https: (and maybe mailto:), never user-supplied strings with a scheme like file: or a custom handler you did not intend to expose.

A navigation guard you can run

The decision logic is plain JavaScript, so you can test it here. This stand-in classifies a URL as "stay in app", "open in the browser" or "block", and runs through typical cases. Use something like it in will-navigate and setWindowOpenHandler.

Node.js Stand-in: classify navigation requests

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.

Notice that plain http: to an outside host is blocked: if you open external links at all, prefer https: only.

Custom protocols: serving your app from app://

Loading file:// pages works, but file:// has quirks: every file is treated as its own opaque origin in some situations, some APIs (service workers, certain fetches, localStorage partitioning) behave oddly, and relative paths can escape your folder. A common modern pattern registers a custom protocol such as app:// and serves your renderer files through a handler, with explicit path checks.

JavaScript
const { app, protocol, net } = require('electron')
const path = require('node:path')
const { pathToFileURL } = require('node:url')

protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { standard: true, secure: true, supportFetchAPI: true } },
])

app.whenReady().then(() => {
  const root = path.join(__dirname, '../renderer')

  protocol.handle('app', (request) => {
    const { pathname } = new URL(request.url)
    const filePath = path.normalize(path.join(root, pathname))
    if (!filePath.startsWith(root + path.sep)) {
      return new Response('Forbidden', { status: 403 })
    }
    return net.fetch(pathToFileURL(filePath).toString())
  })
})

registerSchemesAsPrivileged must be called before the app is ready. The handler maps app://main/index.html to a file, and the startsWith(root) check blocks path traversal such as app://main/../../secret. Try the mapping logic yourself:

Node.js Stand-in: safe path mapping for app://

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.

Both the plain .. and the percent-encoded variant are caught because the path is decoded and normalized before the prefix check. Always do it in that order.

Reloading and history

win.reload(), win.webContents.reloadIgnoringCache(), goBack(), goForward() and navigationHistory (for Electron 30+) manage history. Single-page apps rarely need them, but if your renderer uses hash routing you can respond to did-navigate-in-page to update window titles or menus.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does win.loadFile('index.html') do compared with loadURL?

    loadFile is a convenience for local files; loadURL accepts http, https, file or custom protocol URLs.
  2. 2. How do you stop a page from navigating the window to an outside site?

    will-navigate lets the main process cancel navigations; combine it with setWindowOpenHandler for new windows.
  3. 3. Which return value from setWindowOpenHandler prevents Electron from creating the new window?

    Returning { action: 'deny' } blocks the window; you can open the URL in the default browser instead.
  4. 4. Why decode and normalize a path before the startsWith(root) check in a protocol handler?

    Checking the raw string misses encoded segments and '..' pieces; resolving first reveals the real target path.
  5. 5. When must registerSchemesAsPrivileged be called?

    Privileged schemes have to be registered before the ready event.

Summary

  • loadFile for local pages, loadURL for dev servers, remote pages or custom protocols; both return promises.
  • Use load events (did-fail-load, did-finish-load) to show progress or error pages.
  • Guard navigation with will-navigate and setWindowOpenHandler; open external links with shell.openExternal after validating the scheme.
  • A custom protocol (app://) gives a clean origin and lets you validate paths before serving files.

Next: IPC Overview: Channels and Messages