diff options
Diffstat (limited to 'packages/main/src/infrastructure/electron/impl/lockWebContentsToFile.ts')
-rw-r--r-- | packages/main/src/infrastructure/electron/impl/lockWebContentsToFile.ts | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/packages/main/src/infrastructure/electron/impl/lockWebContentsToFile.ts b/packages/main/src/infrastructure/electron/impl/lockWebContentsToFile.ts new file mode 100644 index 0000000..6b458e0 --- /dev/null +++ b/packages/main/src/infrastructure/electron/impl/lockWebContentsToFile.ts | |||
@@ -0,0 +1,59 @@ | |||
1 | /* | ||
2 | * Copyright (C) 2022 Kristóf Marussy <kristof@marussy.com> | ||
3 | * | ||
4 | * This file is part of Sophie. | ||
5 | * | ||
6 | * Sophie is free software: you can redistribute it and/or modify | ||
7 | * it under the terms of the GNU Affero General Public License as | ||
8 | * published by the Free Software Foundation, version 3. | ||
9 | * | ||
10 | * This program is distributed in the hope that it will be useful, | ||
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
13 | * GNU Affero General Public License for more details. | ||
14 | * | ||
15 | * You should have received a copy of the GNU Affero General Public License | ||
16 | * along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
17 | * | ||
18 | * SPDX-License-Identifier: AGPL-3.0-only | ||
19 | */ | ||
20 | |||
21 | import { WebContents } from 'electron'; | ||
22 | |||
23 | import { getLogger } from '../../../utils/log'; | ||
24 | import type Resources from '../../resources/Resources'; | ||
25 | |||
26 | const log = getLogger('lockWebContentsToFile'); | ||
27 | |||
28 | /** | ||
29 | * Loads the specified file in the webContents and prevent navigating away. | ||
30 | * | ||
31 | * Both navigating away to a different URL and opening a new window will be disallowed. | ||
32 | * | ||
33 | * @param resources The resource handle associated with the paths and URL of the application. | ||
34 | * @param filePath The path to the file in the render package to load. | ||
35 | * @param webContents The webContents to lock. | ||
36 | */ | ||
37 | export default function lockWebContentsToFile( | ||
38 | resources: Resources, | ||
39 | filePath: string, | ||
40 | webContents: WebContents, | ||
41 | ): Promise<void> { | ||
42 | const pageURL = resources.getRendererURL(filePath); | ||
43 | |||
44 | webContents.setWindowOpenHandler(() => ({ action: 'deny' })); | ||
45 | |||
46 | webContents.on('will-navigate', (event, url) => { | ||
47 | if (url !== pageURL) { | ||
48 | log.error( | ||
49 | 'Prevented webContents locked to', | ||
50 | pageURL, | ||
51 | 'from navigating to', | ||
52 | url, | ||
53 | ); | ||
54 | event.preventDefault(); | ||
55 | } | ||
56 | }); | ||
57 | |||
58 | return webContents.loadURL(pageURL); | ||
59 | } | ||