-
Notifications
You must be signed in to change notification settings - Fork 169
/
redirect.ts
48 lines (41 loc) · 1.11 KB
/
redirect.ts
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
import util from "../../shared/util.ts";
import events from "./events.ts";
let routerReady = false;
let preRedirect: URL | null = null;
const onrouterready = (_: Record<string, unknown>) => {
events.off("routerready", onrouterready);
if (preRedirect) {
events.emit("popstate", { type: "popstate", url: preRedirect });
preRedirect = null;
}
routerReady = true;
};
events.on("routerready", onrouterready);
export function redirect(url: string, replace?: boolean) {
const { history, location } = globalThis;
if (!util.isFilledString(url) || !history || !location) {
return;
}
if (url.startsWith("file://") || url.startsWith("mailto:") || url.startsWith("data:")) {
location.href = url;
return;
}
const to = new URL(url, location.href);
if (to.href === location.href) {
return;
}
if (to.host !== location.host) {
location.href = url;
return;
}
if (replace) {
history.replaceState(null, "", to);
} else {
history.pushState(null, "", to);
}
if (routerReady) {
events.emit("popstate", { type: "popstate", url: to });
} else {
preRedirect = to;
}
}