Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: resolve absolute worker url against the current path #1456

Merged
merged 1 commit into from Nov 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
}