Commit ee32d36f authored by Enrique Alcantara's avatar Enrique Alcantara Committed by jerasmus

Add getURLOrigin utility

parent ef5e4f47
......@@ -444,3 +444,16 @@ export function getHTTPProtocol(url) {
export function stripPathTail(path = '') {
return path.replace(/[^/]+$/, '');
}
export function getURLOrigin(url) {
if (!url) {
return window.location.origin;
}
try {
return new URL(url).origin;
} catch (e) {
return null;
}
}
......@@ -814,4 +814,23 @@ describe('URL utility', () => {
expect(urlUtils.stripPathTail(path)).toBe(expected);
});
});
describe('getURLOrigin', () => {
it('when no url passed, returns correct origin from window location', () => {
const origin = 'https://foo.bar';
setWindowLocation({ origin });
expect(urlUtils.getURLOrigin()).toBe(origin);
});
it.each`
url | expectation
${'not-a-url'} | ${null}
${'wss://example.com'} | ${'wss://example.com'}
${'https://foo.bar/foo/bar'} | ${'https://foo.bar'}
`('returns correct origin for $url', ({ url, expectation }) => {
expect(urlUtils.getURLOrigin(url)).toBe(expectation);
});
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment