Line data Source code
1 : // SPDX-License-Identifier: LGPL-2.1-or-later
2 754 : function get_url_root(): string | null {
3 754 : const meta_url_root = document.head.querySelector("meta[name='url-root']");
4 144 : if (meta_url_root instanceof HTMLMetaElement) {
5 144 : return meta_url_root.content.replace(/^\/+|\/+$/g, '');
6 136 : } else {
7 : // fallback for cockpit-ws < 272
8 746 : try {
9 : // Sometimes this throws a SecurityError such as during testing
10 746 : return window.localStorage.getItem('url-root');
11 136 : } catch {
12 136 : return null;
13 136 : }
14 746 : }
15 754 : }
16 754 : export const url_root = get_url_root();
17 :
18 754 : export const transport_origin = window.location.origin;
19 :
20 367 : export function calculate_application(): string {
21 66 : let path = window.location.pathname || "/";
22 367 : let _url_root = url_root;
23 66 : if (window.mock?.pathname)
24 66 : path = window.mock.pathname;
25 66 : if (window.mock?.url_root)
26 66 : _url_root = window.mock.url_root;
27 :
28 70 : if (_url_root && path.indexOf('/' + _url_root) === 0)
29 66 : path = path.replace('/' + _url_root, '') || '/';
30 :
31 344 : if (path.indexOf("/cockpit/") !== 0 && path.indexOf("/cockpit+") !== 0) {
32 344 : if (path.indexOf("/=") === 0)
33 66 : path = "/cockpit+" + path.split("/")[1];
34 : else
35 344 : path = "/cockpit";
36 344 : }
37 :
38 367 : return path.split("/")[1];
39 367 : }
40 :
41 343 : export function calculate_url(suffix?: string): string {
42 343 : if (!suffix)
43 343 : suffix = "socket";
44 343 : const window_loc = window.location.toString();
45 343 : let _url_root = url_root;
46 :
47 62 : if (window.mock?.url)
48 62 : return window.mock.url;
49 62 : if (window.mock?.url_root)
50 62 : _url_root = window.mock.url_root;
51 :
52 343 : let prefix = calculate_application();
53 343 : if (_url_root)
54 66 : prefix = _url_root + "/" + prefix;
55 :
56 342 : if (window_loc.indexOf('http:') === 0) {
57 342 : return "ws://" + window.location.host + "/" + prefix + "/" + suffix;
58 62 : } else if (window_loc.indexOf('https:') === 0) {
59 63 : return "wss://" + window.location.host + "/" + prefix + "/" + suffix;
60 62 : } else {
61 62 : throw new Error("Cockpit must be used over http or https");
62 62 : }
63 343 : }
|