Links: Fix links to other apps outside Grafana when under sub path (#36498)

This commit is contained in:
Torkel Ödegaard
2021-07-07 15:25:59 +02:00
committed by GitHub
parent 3e95c3826a
commit eed1f36613
3 changed files with 9 additions and 17 deletions
@@ -57,7 +57,7 @@ describe('locationUtil', () => {
}); });
test('absolute url with subdirectory subUrl', () => { test('absolute url with subdirectory subUrl', () => {
const urlWithoutMaster = locationUtil.stripBaseFromUrl('http://www.domain.com:9877/thisShouldRemain/subUrl/'); const urlWithoutMaster = locationUtil.stripBaseFromUrl('http://www.domain.com:9877/thisShouldRemain/subUrl/');
expect(urlWithoutMaster).toBe('/thisShouldRemain/subUrl/'); expect(urlWithoutMaster).toBe('http://www.domain.com:9877/thisShouldRemain/subUrl/');
}); });
}); });
+1 -7
View File
@@ -17,16 +17,10 @@ const stripBaseFromUrl = (url: string): string => {
const isAbsoluteUrl = url.startsWith('http'); const isAbsoluteUrl = url.startsWith('http');
let segmentToStrip = appSubUrl; let segmentToStrip = appSubUrl;
if (!url.startsWith('/')) { if (!url.startsWith('/') || isAbsoluteUrl) {
segmentToStrip = `${window.location.origin}${appSubUrl}`; segmentToStrip = `${window.location.origin}${appSubUrl}`;
} }
if (isAbsoluteUrl) {
segmentToStrip = url.startsWith(`${window.location.origin}${appSubUrl}`)
? `${window.location.origin}${appSubUrl}`
: `${window.location.origin}`;
}
return url.length > 0 && url.indexOf(segmentToStrip) === 0 ? url.slice(segmentToStrip.length - stripExtraChars) : url; return url.length > 0 && url.indexOf(segmentToStrip) === 0 ? url.slice(segmentToStrip.length - stripExtraChars) : url;
}; };
@@ -18,20 +18,18 @@ export function interceptLinkClicks(e: MouseEvent) {
e.preventDefault(); e.preventDefault();
href = locationUtil.stripBaseFromUrl(href); href = locationUtil.stripBaseFromUrl(href);
// Ensure old angular urls with no starting '/' are handled the same as before // Ensure old angular urls with no starting '/' are handled the same as before
// Make sure external links are handled correctly // Make sure external links are handled correctly
// That is they where seen as being absolute from app root // That is they where seen as being absolute from app root
if (href[0] !== '/') { if (href[0] !== '/') {
try { // if still contains protocol it's an absolute link to another domain or web application
const external = new URL(href); if (href.indexOf('://')) {
if (external.origin !== window.location.origin) { window.location.href = href;
window.location.href = external.toString(); return;
return; } else {
} href = `/${href}`;
} catch (e) {
console.warn(e);
} }
href = `/${href}`;
} }
locationService.push(href); locationService.push(href);
} }