Skip to content

Commit

Permalink
fix: resolve absolute worker url against the current path (#1456)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Nov 12, 2022
1 parent d67ef9c commit f8d15b4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
31 changes: 24 additions & 7 deletions src/utils/url/getAbsoluteWorkerUrl.test.ts
Expand Up @@ -3,12 +3,29 @@
*/
import { getAbsoluteWorkerUrl } from './getAbsoluteWorkerUrl'

describe('getAbsoluteWorkerUrl', () => {
describe('given a relative worker URL', () => {
it('should return an absolute URL against the current location', () => {
expect(getAbsoluteWorkerUrl('./mockServiceWorker.js')).toEqual(
'http://localhost/mockServiceWorker.js',
)
})
const rawLocation = window.location

afterAll(() => {
Object.defineProperty(window, 'location', {
value: rawLocation,
})
})

it('returns absolute worker url relatively to the root', () => {
expect(getAbsoluteWorkerUrl('./worker.js')).toBe('http://localhost/worker.js')
})

it('returns an absolute worker url relatively to the current path', () => {
Object.defineProperty(window, 'location', {
value: {
href: 'http://localhost/path/to/page',
},
})

expect(getAbsoluteWorkerUrl('./worker.js')).toBe(
'http://localhost/path/to/worker.js',
)

// Leading slash must still resolve to the root.
expect(getAbsoluteWorkerUrl('/worker.js')).toBe('http://localhost/worker.js')
})
4 changes: 2 additions & 2 deletions src/utils/url/getAbsoluteWorkerUrl.ts
Expand Up @@ -2,6 +2,6 @@
* Returns an absolute Service Worker URL based on the given
* relative URL (known during the registration).
*/
export function getAbsoluteWorkerUrl(relativeUrl: string): string {
return new URL(relativeUrl, location.origin).href
export function getAbsoluteWorkerUrl(workerUrl: string): string {
return new URL(workerUrl, location.href).href
}

0 comments on commit f8d15b4

Please sign in to comment.