diff --git a/src/utils/url.test.ts b/src/utils/url.test.ts new file mode 100644 index 0000000000..234690dc40 --- /dev/null +++ b/src/utils/url.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { getLocationSearch } from './url'; + +const mockLocation = (urlString: string) => { + // eslint-disable-next-line compat/compat + const url = new URL(urlString); + vi.spyOn(window, 'location', 'get') + .mockReturnValue({ + ...window.location, + hash: url.hash, + host: url.host, + hostname: url.hostname, + href: url.href, + origin: url.origin, + pathname: url.pathname, + port: url.port, + protocol: url.protocol, + search: url.search + }); +}; + +describe('getLocationSearch', () => { + it('Should work with standard url search', () => { + mockLocation('https://example.com/path?foo#bar'); + expect(getLocationSearch()).toBe('?foo'); + }); + + it('Should work with search in the url hash', () => { + mockLocation('https://example.com/path#bar?foo'); + expect(getLocationSearch()).toBe('?foo'); + }); + + it('Should work with search in the url hash and standard url search', () => { + mockLocation('https://example.com/path?baz#bar?foo'); + expect(getLocationSearch()).toBe('?foo'); + }); + + it('Should return an empty string if there is no search', () => { + mockLocation('https://example.com'); + expect(getLocationSearch()).toBe(''); + }); + + it('Should fallback to the href if there is no hash or search', () => { + vi.spyOn(window, 'location', 'get') + .mockReturnValue({ + ...window.location, + hash: '', + host: '', + hostname: '', + href: 'https://example.com/path#bar?foo', + origin: '', + pathname: '', + port: '', + protocol: '', + search: '' + }); + expect(getLocationSearch()).toBe('?foo'); + }); +}); diff --git a/src/utils/url.ts b/src/utils/url.ts index 1c65b2343a..1c88b3a115 100644 --- a/src/utils/url.ts +++ b/src/utils/url.ts @@ -5,13 +5,19 @@ * @returns The url search string. */ export const getLocationSearch = () => { + // Check location.hash for a search string (this should be the case for our routing library) + let index = window.location.hash.indexOf('?'); + if (index !== -1) { + return window.location.hash.substring(index); + } + // Return location.search if it exists if (window.location.search) { return window.location.search; } - // Check the entire url in case the search string is in the hash - const index = window.location.href.indexOf('?'); + // Fallback to checking the entire url + index = window.location.href.indexOf('?'); if (index !== -1) { return window.location.href.substring(index); }