Skip to content

Commit b23231a

Browse files
committed
Fix external navigations in Electron v20
Electron seems to have changed how 'new-window' works, in addition to deprecating it, so that the previous code double-opened external links. That's annoying, but switching to the new API seems to fix it nicely.
1 parent d76b738 commit b23231a

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

src/index.ts

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -201,8 +201,26 @@ if (!amMainInstance) {
201201
});
202202

203203
// Redirect all navigations & new windows to the system browser
204-
contents.on('will-navigate', handleNavigation);
205-
contents.on('new-window', handleNavigation);
204+
contents.on('will-navigate', (event: Electron.Event, navigationUrl: string) => {
205+
const parsedUrl = new URL(navigationUrl);
206+
207+
checkForUnsafeNavigation(parsedUrl);
208+
if (!isLocalNavigation(parsedUrl)) {
209+
event.preventDefault();
210+
handleExternalNavigation(parsedUrl);
211+
}
212+
});
213+
contents.setWindowOpenHandler((openDetails) => {
214+
const parsedUrl = new URL(openDetails.url);
215+
216+
checkForUnsafeNavigation(parsedUrl);
217+
if (!isLocalNavigation(parsedUrl)) {
218+
handleExternalNavigation(parsedUrl);
219+
return { action: 'deny' };
220+
} else {
221+
return { action: 'allow' };
222+
}
223+
});
206224

207225
contents.on('render-process-gone', (_event, details) => {
208226
if (details.reason === 'clean-exit') return;
@@ -219,17 +237,6 @@ if (!amMainInstance) {
219237
});
220238
});
221239

222-
function handleNavigation(event: Electron.Event, navigationUrl: string) {
223-
const parsedUrl = new URL(navigationUrl);
224-
225-
checkForUnsafeNavigation(parsedUrl);
226-
227-
if (!isLocalNavigation(parsedUrl)) {
228-
event.preventDefault();
229-
handleExternalNavigation(parsedUrl);
230-
}
231-
}
232-
233240
function checkForUnsafeNavigation(url: URL) {
234241
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
235242
// This suggests an attempted XSS attack of some sort, report it:

0 commit comments

Comments
 (0)