electron: [Bug]: Unsanboxed preload running after page with content is loaded (ESM)

Preflight Checklist

Electron Version

28.0.0

What operating system are you using?

Windows

Operating System Version

Windows 10 Family

What arch are you using?

x64

Last Known Working Electron version

No response

Expected Behavior

Electron 28 added support for ESM, the new doc states that:

Unsandboxed ESM preload scripts will run after page load on pages with no content

If the response body for a renderer’s loaded page is completely empty (i.e. Content-Length: 0), its preload script will not block the page load, which may result in race conditions.

If this impacts you, change your response body to have something in it (e.g. an empty html tag (<html></html>)) or swap back to using a CommonJS preload script (.js or .cjs), which will block the page load.

So for an HTML with content, I expect the preload to be run before the page loads:

image

Actual Behavior

For the following HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self';">
  </head>
	
  <body>
    <main>
      <p>
        There is nothing interesting to see here...
      </p>
    </main>
  </body>
</html>

Loaded as:

new BrowserWindow({
  webPreferences: {
    nodeIntegration: false,
    contextIsolation: true,
    sandbox: false,
    preload: /*preload path */,
  }
});

With in package.json:

"type": "module"

The JS file linked to my HTML shows the page is loaded before the preload.

image

For context, listen is a function exposed on the preload with contextBridge.

Testcase Gist URL

No response

Additional Information

I can’t see the Content-Length header in the response headers:

image

The file is loaded from http://localhost:3000/worker.html

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 3
  • Comments: 22 (1 by maintainers)

Commits related to this issue

Most upvoted comments

I am able to reproduce every time with the following setup:

main.js

import { app, BrowserWindow } from "electron";
import path from "node:path";
import { createServer } from "node:http";

const html = String.raw;

(async () => {
  await app.whenReady();

  const server = createServer((req, res) => {
    if (req.url === "/") {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.end(
        html`<html>
          <head>
            <meta charset="utf-8" />
            <title>Electron test</title>
            <script type="module" src="renderer.js"></script>
          </head>
          <body></body>
        </html>`
      );
    } else if (req.url === "/renderer.js") {
      res.writeHead(200, { "Content-Type": "text/javascript" });
      res.end(`console.log("renderer loaded");`);
    }
  });

  server.listen(8080);

  const win = new BrowserWindow({
    webPreferences: {
      contextIsolation: true,
      sandbox: false,
      preload: path.resolve("preload.mjs"),
    },
  });

  win.loadURL("http://localhost:8080");
})();

preload.mjs

console.log("preload loaded");

resulting in the following output in devtools/console:

image

I had the time to search a bit more about this issue, and I managed to pinpoint some elements that trigger it:

  • I can’t reproduce the bug on a basic Electron project that doesn’t use a bunder.
  • When using webpack as bundler, the bug can be reproduced inconsistently by importing files into the preload. The greater the number of nested files imported, the more likely the bug will appear. I can also always reproduce it by importing an external library like rimraf. I don’t know why rimraf in particular though… I have not tried with other libraries.
  • When using Vite as bundler, the bug is even easier to reproduce, it happens inconsistently with a single file import (no nesting needed), and all the time with rimraf.

Test cases:

🟢 No bug - 🔴 Always bug - 🟡 Inconsistent

Action Imports Results (webpack) Results (vite)
Starting the app none 🟢 🟡
files 🔴 🔴
rimraf 🔴 🔴
Reload none 🔴 🔴
files 🔴 🔴
rimraf 🔴 🔴
Force reload none 🟢 🟡
files 🟢 🔴
rimraf 🔴 🔴
Hot reload none 🟢 🟡
files 🟡 🟡
rimraf 🔴 🔴

So yeah, very inconsistent bug… Sadly it’s a blocker for switching an app to ESM.

Bump, issue still present on v32.1.0.

Can confirm that this is also happening to our app, though intermittently, so clearly a race-condition.