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