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