0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-03-10 23:01:26 -05:00

ClientRouter: prevent double execution of scripts when custom swap() only swaps parts of the DOM

This commit is contained in:
Martin Trapp 2025-03-08 08:57:05 +01:00
parent d83f92a204
commit 2262a1196d
4 changed files with 41 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Fixes an edge case where the client router executed scripts twice when used with a custom swap function that only swaps parts of the DOM.

View file

@ -0,0 +1,20 @@
---
import { ClientRouter } from "astro:transitions";
---
<html lang="en">
<head>
<meta charset="utf-8" />
<ClientRouter />
<script is:inline>
console.log("[test] head script");
document.addEventListener("astro:before-swap", e => e.swap = () => {});
</script>
</head>
<body>
<h1>Astro</h1>
<script is:inline>console.log("[test] body script")</script>
<a id="link2" href="/partial-swap?v=2">revisit</a><br/>
<a id="link3" href="/partial-swap?v=3">revisit</a>
</body>
</html>

View file

@ -1619,4 +1619,19 @@ test.describe('View Transitions', () => {
await expect(page).toHaveTitle('Page 1');
expect(lines.join('')).toBe('312233');
});
test('initial scripts are not re-executed after partial swap', async ({ page, astro }) => {
let consoleErrors = [];
page.on('console', (msg) => {
const txt = msg.text();
txt.startsWith("[test] ") && consoleErrors.push(txt.substring(7));
});
await page.goto(astro.resolveUrl('/partial-swap'));
await page.waitForURL('**/partial-swap');
await page.click('#link2');
await page.waitForURL('**/partial-swap?v=2');
await page.click('#link3');
await page.waitForURL('**/partial-swap?v=3');
expect(consoleErrors.join(", "), 'There should only be two executions').toEqual("head script, body script");
});
});

View file

@ -649,6 +649,7 @@ if (inBrowser) {
}
for (const script of document.getElementsByTagName('script')) {
detectScriptExecuted(script);
script.dataset.astroExec = '';
}
}