diff --git a/.changeset/stupid-dolls-fly.md b/.changeset/stupid-dolls-fly.md new file mode 100644 index 000000000000..22fc3bc1ffd4 --- /dev/null +++ b/.changeset/stupid-dolls-fly.md @@ -0,0 +1,5 @@ +--- +"@sveltejs/kit": patch +--- + +[fix] transform link[rel=icon] to be absolute to avoid console error when navigating diff --git a/packages/kit/src/runtime/client/client.js b/packages/kit/src/runtime/client/client.js index 7f4247bf168d..2c629a9bb754 100644 --- a/packages/kit/src/runtime/client/client.js +++ b/packages/kit/src/runtime/client/client.js @@ -1220,6 +1220,13 @@ export function create_client({ target, session, base, trailing_slash }) { } }); + // fix link[rel=icon], because browsers will occasionally try to load relative + // URLs after a pushState/replaceState, resulting in a 404 — see + // https://github.com/sveltejs/kit/issues/3748#issuecomment-1125980897 + for (const link of document.querySelectorAll('link')) { + if (link.rel === 'icon') link.href = link.href; + } + addEventListener('pageshow', (event) => { // If the user navigates to another site and then uses the back button and // bfcache hits, we need to set navigating to null, the site doesn't know diff --git a/packages/kit/test/apps/basics/test/test.js b/packages/kit/test/apps/basics/test/test.js index a89c0abf705f..ddbe9e779b2f 100644 --- a/packages/kit/test/apps/basics/test/test.js +++ b/packages/kit/test/apps/basics/test/test.js @@ -1043,15 +1043,29 @@ test.describe('$app/paths', () => { ); }); - test('replaces %sveltekit.assets% in template with relative path', async ({ page }) => { + // some browsers will re-request assets after a `pushState` + // https://github.com/sveltejs/kit/issues/3748#issuecomment-1125980897 + test('replaces %sveltekit.assets% in template with relative path, and makes it absolute in the client', async ({ + baseURL, + page, + javaScriptEnabled + }) => { + const absolute = `${baseURL}/favicon.png`; + await page.goto('/'); - expect(await page.getAttribute('link[rel=icon]', 'href')).toBe('./favicon.png'); + expect(await page.getAttribute('link[rel=icon]', 'href')).toBe( + javaScriptEnabled ? absolute : './favicon.png' + ); await page.goto('/routing'); - expect(await page.getAttribute('link[rel=icon]', 'href')).toBe('./favicon.png'); + expect(await page.getAttribute('link[rel=icon]', 'href')).toBe( + javaScriptEnabled ? absolute : './favicon.png' + ); await page.goto('/routing/rest/foo/bar/baz'); - expect(await page.getAttribute('link[rel=icon]', 'href')).toBe('../../../../favicon.png'); + expect(await page.getAttribute('link[rel=icon]', 'href')).toBe( + javaScriptEnabled ? absolute : '../../../../favicon.png' + ); }); });