Skip to content

Build your personal knowledge base with Trilium Notes

feat(desktop): open extra windows in the opener's renderer process

Elian Doran642f95b7692b
diff --git a/.claude/skills/developing-electron-desktop/SKILL.md b/.claude/skills/developing-electron-desktop/SKILL.md
index 3f7b9578e7..75c788498e 100644
--- a/.claude/skills/developing-electron-desktop/SKILL.md
+++ b/.claude/skills/developing-electron-desktop/SKILL.md
@@ -31,7 +31,7 @@ apps/desktop/
## Process and security model
- **`nodeIntegration: false`, `contextIsolation: true`, `webviewTag: true`** on every window (`services/window.ts`). The renderer has no Node, no `require("electron")`, no `@electron/remote` (removed — never reintroduce it). Everything crosses through the preload bridge.
-- **`web_contents_security.ts`** vets every `<webview>` in `will-attach-webview` and denies `window.open`, routing allow-listed URLs to the OS. If a new feature needs a popup or a webview privilege, change it there — never relax `webPreferences` at the call site.
+- **`web_contents_security.ts`** vets every `<webview>` in `will-attach-webview` and decides `window.open`: the app shell's root URL becomes an extra window in the opener's renderer process (that is how the client opens new windows — no IPC channel), everything else is denied and allow-listed URLs are routed to the OS. If a new feature needs a popup or a webview privilege, change it there — never relax `webPreferences` at the call site.
- **Main-process handlers validate their input** and never trust a path from the renderer: OS pickers run in the main process (`dialog.ts`, `import.ts`, `restore.ts`) and hand back a location the *user* chose; `import.ts` mints single-use access grants rather than accepting a path; `shell.ts` gates every channel with a validator that throws. Follow the same shape for anything that touches the filesystem or the OS.
- **Secrets stay out of the DB where they must**: `security_settings.ts` reads `data_dir/security.json`, `backup_passphrase.ts` uses the OS keyring — the passphrase must not travel inside the backup it protects.
- **`services/request.ts`** (`ElectronRequestProvider`) uses Electron's `net` so sync honours the system proxy; `referer.ts` keeps hosts that require an http(s) `Referer` working from the `trilium-app://` origin.
diff --git a/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md b/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md
index a60b00937f..cc35f689dc 100644
--- a/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md
+++ b/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md
@@ -17,7 +17,8 @@ In packaged Electron the renderer loads the **entire** UI from `trilium-app://ap
| API call from an **iframe** returns **403** / is cancelled | The frame-origin guard rejected the request: a non-`mainFrame` request whose frame chain contains a non-app (foreign) frame is denied **before** the protocol handler runs. | `installFrameOriginGuard` (`protocol.ts:120`) registers a `webRequest.onBeforeRequest` filter; the pure policy is `isRequestorChainTrusted(resourceType, frameUrls)` (`protocol.ts:143`) — `mainFrame` always allowed; otherwise every committed frame must be the app shell or `devtools:`. A second, weaker check `isDispatchOriginAllowed` (`protocol.ts:173`) 403s any request that *positively* attests a foreign `Origin` (only navigation-style requests carry one). |
| **`<webview>` won't attach** / log shows `Blocked <webview> attach requesting [...]` | The attach requested a banned capability (`preload`, `nodeIntegration`, `nodeIntegrationInSubFrames`, `webSecurity:false`, `allowRunningInsecureContent`) or the wrong/empty session partition. | `hardenWebviewPreferences` (`web_contents_security.ts:79`), called from the `will-attach-webview` hook (`:50`), returns the violation list; a non-empty list `preventDefault()`s the attach. The partition **must** exactly equal `WEBVIEW_SESSION_PARTITION` (`"persist:webview"`) — an unset/empty/different partition is a violation (`:111-115`). The legit Web View note always declares it. |
| **Permission denied** (camera, mic, geolocation, clipboard-read, notifications from a remote embed, …) | Not in `PERMISSION_ALLOWLIST` for that session kind, or the request origin isn't the app shell. Unset handlers would GRANT everything, so deny-by-default is enforced explicitly. | `PERMISSION_ALLOWLIST` (`web_contents_security.ts:150`): `app` = `clipboard-sanitized-write`, `fullscreen`, `notifications`; `guest` = `fullscreen` only. `isPermissionAllowedForOrigin` (`:176`) additionally requires the request to come from `trilium-app://app` (except `fullscreen`, allowed for any origin). Installed on both the default and `WEBVIEW_SESSION_PARTITION` sessions (`:63-66`). |
-| `window.open` / `target=_blank` does nothing, or a note link opens in the OS browser | By design: every window-open is denied; for app windows the URL is re-validated through the same scheme allowlist and routed to the OS browser. | `installWindowOpenPolicy` (`web_contents_security.ts:218`) reuses `validateOpenExternalUrl` from `shell.ts`, so a note-content link can't bypass the Follina/`smb:` allowlist. `<webview>` guests are denied outright (no external dispatch). |
+| `window.open` / `target=_blank` does nothing, or a note link opens in the OS browser | By design: only the app shell's root URL (`isNavigationAllowed`, query string and hash allowed) is allowed — that is the client's own "open in new window", and Chromium creates it in the opener's renderer process; every other window-open is denied, and for app windows the URL is re-validated through the same scheme allowlist and routed to the OS browser. | `installWindowOpenPolicy` (`web_contents_security.ts`) returns `allow` + `outlivesOpener` + the `extraWindowOptions()` that `setupWindowing()` supplies; otherwise it reuses `validateOpenExternalUrl` from `shell.ts`, so a note-content link can't bypass the Follina/`smb:` allowlist. `<webview>` guests are denied outright (no external dispatch, not even for the app URL). |
+| A window opened from the client is **blank**, or has no `window.electronApi` | The `window.open` child was built without a preload — children inherit only the security-related `webPreferences` (`sandbox`, `nodeIntegration`, …), never `preload` — or its initial navigation was blocked by the guard. | `getExtraWindowOptions()` (`window.ts`) must include `webPreferences.preload`; `setupWindowing()` passes it as `extraWindowOptions`. `did-create-window` on the opener runs `adoptExtraWindow()` (menu bar, spellcheck, focus tracking). The `--new-window` command line still uses main-process `createExtraWindow()`, which has no opener. |
| A link/drag navigates an **app window away from Trilium** and gets blocked | The navigation guard only allows the app shell root. | `isNavigationAllowed(targetUrl)` (`web_contents_security.ts:199`): allowed only for `trilium-app:` + the app host at root path (`/`, `/?`, or empty). `<webview>` guests are exempt (they're embedded browsers). The old `localhost` carve-out was removed as dangerous. |
| YouTube embed shows "video player configuration error" | On desktop the renderer origin is `trilium-app://app` (not http(s)), so the embed request goes out with no `Referer`. | `installYouTubeEmbedReferer` (`web_contents_security.ts:293`) injects `Referer: https://triliumnotes.org/` (a non-youtube.com origin) for the embed hosts, never overwriting an existing header. |
diff --git a/apps/client/src/components/entrypoints.spec.ts b/apps/client/src/components/entrypoints.spec.ts
index e9ea180fe5..c53381088c 100644
--- a/apps/client/src/components/entrypoints.spec.ts
+++ b/apps/client/src/components/entrypoints.spec.ts
@@ -21,14 +21,14 @@ describe("openInWindowCommand", () => {
expect(String(url)).toMatch(/#root\/abc123$/);
});
- it("hands only the hash to Electron, which builds the URL itself", async () => {
- const createExtraWindow = vi.fn();
- window.electronApi = { window: { createExtraWindow } } as unknown as ElectronApi;
- const open = vi.spyOn(window, "open");
+ it("uses window.open on desktop too; the main process adopts the child", async () => {
+ window.electronApi = {} as unknown as ElectronApi;
+ const open = vi.spyOn(window, "open").mockReturnValue(null);
await entrypoints.openInWindowCommand({ notePath: "root/abc123", hoistedNoteId: "root" });
- expect(createExtraWindow).toHaveBeenCalledWith("#root/abc123");
- expect(open).not.toHaveBeenCalled();
+ const [url] = open.mock.calls[0];
+ expect(String(url)).toMatch(/[?&]extraWindow=1/);
+ expect(String(url)).toMatch(/#root\/abc123$/);
});
});
diff --git a/apps/client/src/components/entrypoints.ts b/apps/client/src/components/entrypoints.ts
index e932f49f20..58d5d64ac6 100644
--- a/apps/client/src/components/entrypoints.ts
+++ b/apps/client/src/components/entrypoints.ts
@@ -139,11 +139,9 @@ export default class Entrypoints extends Component {
async openInWindowCommand({ notePath, hoistedNoteId, viewScope, splits, activeSplit }: NoteCommandData) {
const target = { notePath, hoistedNoteId, viewScope, splits, activeSplit };
- if (window.electronApi) {
- window.electronApi.window.createExtraWindow(linkService.calculateHash(target));
- } else {
- window.open(linkService.calculateExtraWindowUrl(target), "", "width=1000,height=800");
- }
+ // On desktop the main process turns this into an extra window that shares
+ // this renderer's process (`installWindowOpenPolicy`).
+ window.open(linkService.calculateExtraWindowUrl(target), "", "width=1000,height=800");
}
async openNewWindowCommand() {
diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.ts
index eaca6a4bfc..0ef7b77092 100644
--- a/apps/desktop/src/preload.spec.ts
+++ b/apps/desktop/src/preload.spec.ts
@@ -172,14 +172,6 @@ describe("preload script", () => {
expect(ipcRendererSent).toContainEqual({ channel: "close-window", args: [] });
});
- it("createExtraWindow sends correct IPC message", () => {
- win().createExtraWindow("#root/abc123");
- expect(ipcRendererSent).toContainEqual({
- channel: "create-extra-window",
- args: [{ extraWindowHash: "#root/abc123" }]
- });
- });
-
it("isAlwaysOnTop uses sendSync", () => {
ipcRendererSyncResults.set("is-always-on-top:undefined", true);
expect(win().isAlwaysOnTop()).toBe(true);
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 357314662e..c7cd50e06a 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -62,9 +62,6 @@ contextBridge.exposeInMainWorld("electronApi", {
closeWindow() {
ipcRenderer.send("close-window");
},
- createExtraWindow(extraWindowHash: string) {
- ipcRenderer.send("create-extra-window", { extraWindowHash });
- },
isAlwaysOnTop(): boolean {
return ipcRenderer.sendSync("is-always-on-top");
},
diff --git a/apps/desktop/src/services/web_contents_security.spec.ts b/apps/desktop/src/services/web_contents_security.spec.ts
index 36f3b6b64c..e971597084 100644
--- a/apps/desktop/src/services/web_contents_security.spec.ts
+++ b/apps/desktop/src/services/web_contents_security.spec.ts
@@ -93,8 +93,18 @@ vi.mock("electron", () => ({
const { hardenWebviewPreferences, isNavigationAllowed, isPermissionAllowed, isPermissionAllowedForOrigin, setupWebContentsSecurity, withYouTubeEmbedReferer } = await import("./web_contents_security.js");
+/**
+ * Stands in for what `setupWindowing()` supplies: the options an allowed
+ * `window.open` child is built with.
+ */
+const SECURITY_OPTIONS = {
+ extraWindowOptions: () => ({ width: 1000, webPreferences: { preload: "preload.cjs" } })
+};
+
interface WindowOpenResult {
action: "allow" | "deny";
+ outlivesOpener?: boolean;
+ overrideBrowserWindowOptions?: Electron.BrowserWindowConstructorOptions;
}
/**
@@ -234,7 +244,7 @@ describe("setupWebContentsSecurity", () => {
beforeEach(() => {
resetState();
- setupWebContentsSecurity();
+ setupWebContentsSecurity(SECURITY_OPTIONS);
});
/** Simulates a window being created and then a <webview> attaching inside it. */
@@ -348,7 +358,7 @@ describe("isPermissionAllowedForOrigin", () => {
describe("permission handlers", () => {
beforeEach(async () => {
resetState();
- setupWebContentsSecurity();
+ setupWebContentsSecurity(SECURITY_OPTIONS);
// Installation is gated on app.whenReady(); flush the microtask queue.
await Promise.resolve();
});
@@ -450,7 +460,7 @@ describe("withYouTubeEmbedReferer", () => {
describe("YouTube embed referer header", () => {
beforeEach(async () => {
resetState();
- setupWebContentsSecurity();
+ setupWebContentsSecurity(SECURITY_OPTIONS);
await Promise.resolve(); // installation is gated on app.whenReady()
});
@@ -472,7 +482,7 @@ describe("YouTube embed referer header", () => {
describe("window-open policy", () => {
beforeEach(() => {
resetState();
- setupWebContentsSecurity();
+ setupWebContentsSecurity(SECURITY_OPTIONS);
});
it("denies the popup and opens allowlisted URLs in the OS browser", async () => {
@@ -512,14 +522,44 @@ describe("window-open policy", () => {
expect(state.errors[0]).toContain("https://bad.example");
});
+ it("allows the app shell's root URL as an extra window in the opener's process", async () => {
+ const contents = createContents();
+
+ expect(contents.openWindow("trilium-app://app/?extraWindow=1#root/abc")).toEqual({
+ action: "allow",
+ outlivesOpener: true,
+ overrideBrowserWindowOptions: SECURITY_OPTIONS.extraWindowOptions()
+ });
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(state.shellOpenExternal).toEqual([]);
+ expect(state.errors).toEqual([]);
+ });
+
+ it("denies app-scheme URLs off the shell root without dispatching to the OS", async () => {
+ const contents = createContents();
+
+ for (const url of ["trilium-app://app/somewhere", "trilium-app://evil/"]) {
+ expect(contents.openWindow(url)).toEqual({ action: "deny" });
+ }
+ await new Promise((r) => setTimeout(r, 0));
+
+ // `trilium-app:` is not an allowlisted external scheme either.
+ expect(state.shellOpenExternal).toEqual([]);
+ expect(state.errors).toHaveLength(2);
+ });
+
it("denies window.open from webview guests without dispatching to the OS", async () => {
const contents = createContents("webview");
+ // Not even the app shell URL: a guest must never spawn a privileged window.
expect(contents.openWindow("https://example.com")).toEqual({ action: "deny" });
+ const appUrl = "trilium-app://app/?extraWindow=1";
+ expect(contents.openWindow(appUrl)).toEqual({ action: "deny" });
await new Promise((r) => setTimeout(r, 0));
expect(state.shellOpenExternal).toEqual([]);
- expect(state.errors).toHaveLength(1);
+ expect(state.errors).toHaveLength(2);
expect(state.errors[0]).toContain("https://example.com");
});
});
@@ -527,13 +567,15 @@ describe("window-open policy", () => {
describe("navigation guard", () => {
beforeEach(() => {
resetState();
- setupWebContentsSecurity();
+ setupWebContentsSecurity(SECURITY_OPTIONS);
});
it("only allows the app shell at its root path", () => {
expect(isNavigationAllowed("trilium-app://app/")).toBe(true);
// Root "/?" path is allowed.
expect(isNavigationAllowed("trilium-app://app/?")).toBe(true);
+ // The extra-window URL: root path with a query string and a hash.
+ expect(isNavigationAllowed("trilium-app://app/?extraWindow=1#root/abc")).toBe(true);
// App shell but non-root path is blocked (in-page SPA routing / hostile).
expect(isNavigationAllowed("trilium-app://app/somewhere")).toBe(false);
diff --git a/apps/desktop/src/services/web_contents_security.ts b/apps/desktop/src/services/web_contents_security.ts
index 090ff39f0c..628f4e333b 100644
--- a/apps/desktop/src/services/web_contents_security.ts
+++ b/apps/desktop/src/services/web_contents_security.ts
@@ -21,14 +21,25 @@ import { isTriliumAppShellUrl, TRILIUM_APP_HOST, TRILIUM_APP_SCHEME } from "./tr
* web preferences the embedder requested.
*/
+/** What the window-open policy needs from `window.ts`. */
+export interface WebContentsSecurityOptions {
+ /**
+ * Constructor options for the extra window a `window.open` call from an app
+ * window creates. Must include `webPreferences.preload`: a child window
+ * inherits only the security-related preferences of its opener.
+ */
+ extraWindowOptions(): Electron.BrowserWindowConstructorOptions;
+}
+
/**
* Registers a main-process hook that applies a uniform security policy to
* every WebContents the app ever creates (main, extra, setup and print
* windows as well as `<webview>` guests):
*
* - vets every `<webview>` before it attaches,
- * - denies all window-open requests, routing allowlisted URLs to the OS
- * browser instead,
+ * - answers window-open requests: the app shell's own root URL becomes an
+ * extra window in the opener's renderer process, every other URL is denied
+ * and, if allowlisted, routed to the OS browser instead,
* - blocks navigation away from the app shell,
* - installs deny-by-default permission handlers on both the app session and
* the dedicated `<webview>` guest session.
@@ -41,7 +52,7 @@ import { isTriliumAppShellUrl, TRILIUM_APP_HOST, TRILIUM_APP_SCHEME } from "./tr
*
* Call once during startup, before any window is created.
*/
-export function setupWebContentsSecurity() {
+export function setupWebContentsSecurity(options: WebContentsSecurityOptions) {
electron.app.on("web-contents-created", (_event, webContents) => {
webContents.on("will-attach-webview", (attachEvent, webPreferences, params) => {
// Depending on the Electron version the `partition` attribute
@@ -54,7 +65,7 @@ export function setupWebContentsSecurity() {
}
});
- installWindowOpenPolicy(webContents);
+ installWindowOpenPolicy(webContents, options.extraWindowOptions);
installNavigationGuard(webContents);
});
@@ -195,10 +206,12 @@ export function isPermissionAllowedForOrigin(kind: SessionKind, permission: stri
/**
* Decides whether a renderer-initiated navigation (link click, drag & drop,
- * meta refresh) may proceed. Only the app shell itself is allowed: the
- * `trilium-app://app` origin (the sole host ever served — see the loadURL
- * call sites), and only at the root path. Anything deeper is in-page SPA
- * routing (which `will-navigate` does not fire for) or hostile.
+ * meta refresh) can proceed, and which `window.open` URLs become extra
+ * windows. Only the app shell itself is allowed: the `trilium-app://app`
+ * origin (the sole host ever served — see the loadURL call sites), and only
+ * at the root path; the query string (`?extraWindow=1`) and the hash are not
+ * part of the check. Anything deeper is in-page SPA routing (which
+ * `will-navigate` does not fire for) or hostile.
*
* `localhost` was previously allowed too, from the era when the desktop
* renderer was served over `http://127.0.0.1:<port>`. The custom-protocol
@@ -210,28 +223,50 @@ export function isNavigationAllowed(targetUrl: string): boolean {
const parsedUrl = url.parse(targetUrl);
const isAppShell = parsedUrl.protocol === `${TRILIUM_APP_SCHEME}:` && parsedUrl.hostname === TRILIUM_APP_HOST;
- return isAppShell && (!parsedUrl.path || parsedUrl.path === "/" || parsedUrl.path === "/?");
+ return isAppShell && (!parsedUrl.pathname || parsedUrl.pathname === "/");
}
/**
- * Denies every window-open request (`window.open`, `target=_blank`). For app
- * windows the URL is routed to the OS browser instead, after passing the same
- * scheme allowlist as the open-external IPC channel — a link in note content
- * is just as attacker-controllable as an IPC payload, so Follina-class
- * (`ms-msdt:`) and credential-leak (`smb:`) URLs must not bypass it here.
+ * Decides every window-open request (`window.open`, `target=_blank`).
+ *
+ * The app shell's root URL, which `isNavigationAllowed` accepts, is how the
+ * client opens an extra window. It is allowed: Chromium creates a
+ * `window.open` child in the opener's renderer process, so the new window
+ * skips the process launch and reuses the scripts the opener has already
+ * compiled. `overrideBrowserWindowOptions` takes precedence over the call's
+ * `features` string, so a page cannot loosen `webPreferences` through it, and
+ * `outlivesOpener` keeps the child open after its opener closes, like a
+ * window the main process created.
+ *
+ * Every other URL is denied. For app windows it is routed to the OS browser
+ * instead, after passing the same scheme allowlist as the open-external IPC
+ * channel: a link in note content is as attacker-controllable as an IPC
+ * payload, so Follina-class (`ms-msdt:`) and credential-leak (`smb:`) URLs
+ * must not bypass it here.
*
* `<webview>` guests are denied without the external dispatch: the tag never
- * sets `allowpopups`, so popups are already impossible there — this keeps it
- * that way even if a future Electron version changes the default, and stops
- * remote pages from triggering OS protocol handlers.
+ * sets `allowpopups`, so popups are already impossible there. This keeps it
+ * that way if a future Electron version changes the default, and stops remote
+ * pages from triggering OS protocol handlers.
*/
-function installWindowOpenPolicy(webContents: Electron.WebContents) {
+function installWindowOpenPolicy(
+ webContents: Electron.WebContents,
+ extraWindowOptions: () => Electron.BrowserWindowConstructorOptions
+) {
webContents.setWindowOpenHandler((details) => {
if (webContents.getType() === "webview") {
getLog().error(`Blocked window.open from <webview> guest for URL: ${details.url}`);
return { action: "deny" };
}
+ if (isNavigationAllowed(details.url)) {
+ return {
+ action: "allow",
+ outlivesOpener: true,
+ overrideBrowserWindowOptions: extraWindowOptions()
+ };
+ }
+
async function openExternal() {
const validated = validateOpenExternalUrl(details.url);
await electron.shell.openExternal(validated.toString());
diff --git a/apps/desktop/src/services/window.spec.ts b/apps/desktop/src/services/window.spec.ts
index c37eb3a5f5..33c12dc337 100644
--- a/apps/desktop/src/services/window.spec.ts
+++ b/apps/desktop/src/services/window.spec.ts
@@ -254,6 +254,7 @@ vi.mock("@triliumnext/core", async (importOriginal) => {
const windowService = (await import("./window.js")).default;
const { setupWindowing } = await import("./window.js");
const { markStartupMetric } = await import("./startup_metrics.js");
+const { setupWebContentsSecurity } = await import("./web_contents_security.js");
function fireOn(channel: string, event: unknown, ...args: unknown[]) {
const fn = state.ipcOn.get(channel);
@@ -418,6 +419,21 @@ describe("window service", () => {
expect(win.loadURL).toHaveBeenCalledWith("trilium-app://app/?extraWindow=1#root/abc");
expect(win.webContents.session.setSpellCheckerLanguages).toHaveBeenCalled();
});
+
+ it("adopts a window the renderer opened through window.open", async () => {
+ state.optionBools = { spellCheckEnabled: false };
+ await windowService.createExtraWindow("#opener");
+ const opener = state.windows[state.windows.length - 1];
+
+ const child = new FakeBrowserWindow();
+ opener.webContents.fire("did-create-window", child);
+
+ expect(child.setMenuBarVisibility).toHaveBeenCalledWith(false);
+ expect(child.webContents.session.setSpellCheckerEnabled).toHaveBeenCalledWith(false);
+ state.ipcEmit.mockClear();
+ child.fire("focus");
+ expect(state.ipcEmit).toHaveBeenCalledWith("reload-tray");
+ });
});
describe("createSetupWindow / closeSetupWindow", () => {
@@ -769,10 +785,13 @@ describe("window service", () => {
new FakeBrowserWindow();
});
- it("create-extra-window invokes createExtraWindow", async () => {
- fireOn("create-extra-window", makeEvent(), { extraWindowHash: "#h" });
- await new Promise((r) => setTimeout(r, 0));
- expect(state.windows.some(w => w.loadURL.mock.calls.length > 0)).toBe(true);
+ it("hands the window-open policy the extra-window options, preload included", () => {
+ const [options] = vi.mocked(setupWebContentsSecurity).mock.calls.at(-1) ?? [];
+ const extraWindowOptions = options?.extraWindowOptions();
+ expect(extraWindowOptions?.width).toBe(1000);
+ const preload = extraWindowOptions?.webPreferences?.preload;
+ expect(preload).toMatch(/preload\.(compiled\.)?cjs$/);
+ expect(extraWindowOptions?.webPreferences?.nodeIntegration).toBe(false);
});
it("reload-all-windows reloads every window", () => {
diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.ts
index 7728c9525b..3580a3d1fe 100644
--- a/apps/desktop/src/services/window.ts
+++ b/apps/desktop/src/services/window.ts
@@ -63,12 +63,24 @@ function trackWindowFocus(win: BrowserWindow) {
});
}
+/**
+ * Opens an extra window from the main process, for callers with no renderer to
+ * open it from (the `--new-window` command line). The client opens its own
+ * extra windows through `window.open`, which `installWindowOpenPolicy` turns
+ * into a window in the opener's renderer process; both paths end in
+ * `adoptExtraWindow()`.
+ */
async function createExtraWindow(extraWindowHash: string) {
- const spellcheckEnabled = optionService.getOptionBool("spellCheckEnabled");
-
const { BrowserWindow } = await import("electron");
- const win = new BrowserWindow({
+ const win = new BrowserWindow(getExtraWindowOptions());
+ win.loadURL(`${TRILIUM_APP_BASE_URL}?extraWindow=1${extraWindowHash}`);
+ adoptExtraWindow(win);
+}
+
+/** Constructor options shared by both ways an extra window is created. */
+function getExtraWindowOptions(): BrowserWindowConstructorOptions {
+ return {
width: 1000,
height: 800,
title: "Trilium Notes",
@@ -85,13 +97,13 @@ async function createExtraWindow(extraWindowHash: string) {
},
...getWindowExtraOpts(),
icon: getIcon()
- });
+ };
+}
+/** Per-window wiring for an extra window, whichever way it was created. */
+function adoptExtraWindow(win: BrowserWindow) {
win.setMenuBarVisibility(false);
- win.loadURL(`${TRILIUM_APP_BASE_URL}?extraWindow=1${extraWindowHash}`);
-
- configureWebContents(win.webContents, spellcheckEnabled);
-
+ configureWebContents(win.webContents, optionService.getOptionBool("spellCheckEnabled"));
trackWindowFocus(win);
}
@@ -213,6 +225,11 @@ async function configureWebContents(webContents: WebContents, spellcheckEnabled:
setupSpellcheckForSession(webContents.session, spellcheckEnabled);
setupExportRevealForSession(webContents.session);
+ // `window.open` from this renderer creates an extra window in the same
+ // process (see installWindowOpenPolicy); it needs the same wiring as one
+ // the main process created.
+ webContents.on("did-create-window", (child) => adoptExtraWindow(child));
+
// Forward full-screen events to the renderer via IPC.
const win = electron.BrowserWindow.fromWebContents(webContents);
if (win) {
@@ -477,7 +494,7 @@ export function setupWindowing() {
// to every WebContents the app creates. Installed here rather than left to
// each entry point so a new Electron launcher cannot silently ship without
// the renderer/main security boundary.
- setupWebContentsSecurity();
+ setupWebContentsSecurity({ extraWindowOptions: getExtraWindowOptions });
// Mark a genuine quit so the close-to-tray interceptor lets windows close for
// real. Fires for every quit path (Cmd+Q, tray "Quit", app menu, OS shutdown).
@@ -485,10 +502,6 @@ export function setupWindowing() {
isQuitting = true;
});
- electron.ipcMain.on("create-extra-window", (_event, arg) => {
- createExtraWindow(arg.extraWindowHash);
- });
-
electron.ipcMain.on("reload-all-windows", () => {
for (const win of electron.BrowserWindow.getAllWindows()) {
win.reload();
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index 2238437104..fa28234eb8 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -126,12 +126,6 @@ export interface ElectronWindowApi {
/** Closes the current window. */
closeWindow(): void;
- /**
- * Opens a new top-level Trilium window navigated to the given hash route.
- * @param extraWindowHash The URL hash fragment (without the leading `#`) for the new window.
- */
- createExtraWindow(extraWindowHash: string): void;
-
/** Synchronously returns whether the window is pinned above all others. */
isAlwaysOnTop(): boolean;