Automatically prefix 'https://' to redirected URLs if they fail parsing.

This commit is contained in:
Bauke 2022-11-21 12:43:56 +01:00
parent 6ab041df93
commit 2acb8d804b
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
6 changed files with 17 additions and 8 deletions

View File

@ -68,7 +68,16 @@ browser.webNavigation.onBeforeNavigate.addListener(async (details) => {
break; break;
} }
const redirectedUrl = redirect.redirect(url); let redirectedUrl = redirect.redirect(url);
if (typeof redirectedUrl === 'string') {
try {
redirectedUrl = new URL(redirectedUrl);
} catch {
redirectedUrl = `https://${redirectedUrl as string}`;
redirectedUrl = new URL(redirectedUrl);
}
}
await browser.tabs.update(details.tabId, {url: redirectedUrl.href}); await browser.tabs.update(details.tabId, {url: redirectedUrl.href});
await browser.storage.local.set({ await browser.storage.local.set({
latestTime: Date.now(), latestTime: Date.now(),

View File

@ -48,5 +48,5 @@ export abstract class Redirect {
return false; return false;
} }
public abstract redirect(url: URL | string): URL; public abstract redirect(url: URL | string): URL | string;
} }

View File

@ -8,7 +8,7 @@ export * from './hostname.js';
export * from './regex.js'; export * from './regex.js';
export * from './simple.js'; export * from './simple.js';
export type Redirects = HostnameRedirect | SimpleRedirect; export type Redirects = HostnameRedirect | RegexRedirect | SimpleRedirect;
export function parseRedirect( export function parseRedirect(
parameters: RedirectParameters, parameters: RedirectParameters,

View File

@ -1,9 +1,9 @@
import {Redirect} from './base.js'; import {Redirect} from './base.js';
export class RegexRedirect extends Redirect { export class RegexRedirect extends Redirect {
public redirect(redirect: URL | string): URL { public redirect(redirect: URL | string): string {
const url = redirect instanceof URL ? redirect.href : redirect; const url = redirect instanceof URL ? redirect.href : redirect;
const regex = new RegExp(this.parameters.matcherValue, 'gi'); const regex = new RegExp(this.parameters.matcherValue, 'gi');
return new URL(url.replace(regex, this.parameters.redirectValue)); return url.replace(regex, this.parameters.redirectValue);
} }
} }

View File

@ -1,7 +1,7 @@
import {Redirect} from './base.js'; import {Redirect} from './base.js';
export class SimpleRedirect extends Redirect { export class SimpleRedirect extends Redirect {
public redirect(): URL { public redirect(): string {
return new URL(this.parameters.redirectValue); return this.parameters.redirectValue;
} }
} }

View File

@ -84,7 +84,7 @@ test('Redirect.redirect', (t) => {
t.snapshot( t.snapshot(
{ {
original: url instanceof URL ? url.href : url, original: url instanceof URL ? url.href : url,
redirected: redirect.redirect(url).href, redirected: new URL(redirect.redirect(url)).href,
}, },
`${index} ${redirect.constructor.name}`, `${index} ${redirect.constructor.name}`,
); );