-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcustom-protocol.mjs
More file actions
49 lines (42 loc) · 1.42 KB
/
Copy pathcustom-protocol.mjs
File metadata and controls
49 lines (42 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { readFile } from 'node:fs/promises';
import { extname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Application } from '../index.js';
const directory = fileURLToPath(new URL('./assets/custom-protocol/', import.meta.url));
const root = resolve(directory);
const mimeTypes = {
'.css': 'text/css',
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
};
const app = new Application();
const window = app.createBrowserWindow({ title: 'Custom Protocol Example' });
window.registerProtocol('app', async (request) => {
const url = new URL(request.url);
const pathname = decodeURIComponent(url.pathname).replace(/^\/+/, '') || 'index.html';
const filePath = resolve(root, pathname);
if (relative(root, filePath).startsWith('..')) {
return {
statusCode: 403,
body: Buffer.from('Forbidden'),
mimeType: 'text/plain; charset=utf-8',
};
}
try {
return {
statusCode: 200,
body: await readFile(filePath),
mimeType: mimeTypes[extname(filePath)] ?? 'application/octet-stream',
};
} catch {
return {
statusCode: 404,
body: Buffer.from(`Not found: ${url.pathname}`),
mimeType: 'text/plain; charset=utf-8',
};
}
});
window.createWebview({ url: 'app://localhost/index.html' }).openDevtools();
app.run();