Skip to content

Commit 08978bf

Browse files
authored
fix: don't execute scripts inside @html when instantiated on the client (#10556)
In Svelte 4, scripts inside `@html` were not executed when it was created client-side. This is because `innerHTML = ..` which was used under the hood does not execute scripts due to security reasons. This adjusts the code so the same is true for Svelte 5.
1 parent b80d9bd commit 08978bf

File tree

4 files changed

+19
-1
lines changed

4 files changed

+19
-1
lines changed

.changeset/moody-carrots-lay.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"svelte": patch
3+
---
4+
5+
fix: don't execute scripts inside `@html` when instantiated on the client

packages/svelte/src/internal/client/reconciler.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,9 @@ export function reconcile_html(target, value, svg) {
103103
if (svg) {
104104
html = `<svg>${html}</svg>`;
105105
}
106-
var content = create_fragment_with_script_from_html(html);
106+
// Don't use create_fragment_with_script_from_html here because that would mean script tags are executed.
107+
// @html is basically `.innerHTML = ...` and that doesn't execute scripts either due to security reasons.
108+
var content = create_fragment_from_html(html);
107109
if (svg) {
108110
content = /** @type {DocumentFragment} */ (/** @type {unknown} */ (content.firstChild));
109111
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { test } from '../../assert';
2+
3+
export default test({
4+
// Test that @html does not execute scripts when instantiated in the client.
5+
// Needs to be in this test suite because JSDOM does not quite get this right.
6+
html: `<div></div><script>document.body.innerHTML = 'this should not be executed'</script>`,
7+
skip_if_ssr: 'permanent',
8+
skip_if_hydrate: 'permanent'
9+
});
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<div></div>
2+
{@html `<script>document.body.innerHTML = 'this should not be executed'</script>`}

0 commit comments

Comments
 (0)