Skip to content

Commit

Permalink
On desktop apps, the resource URLs became absolute paths and they are…
Browse files Browse the repository at this point in the history
… resolved to absolute file paths through a handler registered via protocol.interceptFileProtocol
  • Loading branch information
whitphx committed Dec 4, 2022
1 parent d32158f commit 6a50bef
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
30 changes: 28 additions & 2 deletions packages/desktop/electron/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { app, BrowserWindow, ipcMain } from "electron";
import { app, BrowserWindow, ipcMain, protocol } from "electron";
import * as url from "url";
import * as path from "path";
import * as fsPromises from "fs/promises";
import { walkRead } from "./file";
Expand Down Expand Up @@ -41,7 +42,17 @@ const createWindow = () => {
);

if (app.isPackaged || process.env.NODE_ENV === "production") {
mainWindow.loadFile(path.resolve(__dirname, "../index.html"));
// Use .loadURL() with an absolute URL based on "/"
// because absolute URLs with the file:// scheme will be resolved
// to absolute file paths based on the special handler
// registered through `interceptFileProtocol` below.
mainWindow.loadURL(
url.format({
pathname: "/index.html",
protocol: "file:",
slashes: true,
})
);
} else {
mainWindow.loadURL("http://localhost:3000");
}
Expand All @@ -55,6 +66,21 @@ const createWindow = () => {
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
// Resolve absolute paths based on the bundled directory.
// It is assumed that the resource paths are absolute paths starting with "/",
// which is configured at `package.json` with the `"homepage"` field.
// Ref: https://github.com/electron/electron/issues/4612#issuecomment-189116655
const bundleBasePath = path.resolve(__dirname, "..");
protocol.interceptFileProtocol("file", function (req, callback) {
const urlWithoutScheme = req.url.slice(7); // 7 = "file://".length
if (path.isAbsolute(urlWithoutScheme)) {
const resolvedFilePath = path.join(bundleBasePath, urlWithoutScheme);
callback(path.normalize(resolvedFilePath));
} else {
callback(urlWithoutScheme);
}
});

createWindow();

app.on("activate", () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@stlite/desktop",
"version": "0.16.1",
"license": "Apache-2.0",
"homepage": "./",
"homepage": "/",
"main": "./build/electron/main.js",
"files": [
"build",
Expand Down

0 comments on commit 6a50bef

Please sign in to comment.