Skip to content

fix: cleanup event handlers on media elements #16005

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

Merged
merged 2 commits into from
May 26, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/thin-dolls-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: cleanup event handlers on media elements
11 changes: 9 additions & 2 deletions packages/svelte/src/internal/client/dom/elements/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,15 @@ export function event(event_name, dom, handler, capture, passive) {
var options = { capture, passive };
var target_handler = create_event(event_name, dom, handler, options);

// @ts-ignore
if (dom === document.body || dom === window || dom === document) {
if (
dom === document.body ||
// @ts-ignore
dom === window ||
// @ts-ignore
dom === document ||
// Firefox has quirky behavior, it can happen that we still get "canplay" events when the element is already removed
dom instanceof HTMLMediaElement
) {
teardown(() => {
dom.removeEventListener(event_name, target_handler, options);
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
import { expect, vi } from 'vitest';

const handler = vi.fn();

export default test({
props: {
handler
},
async test({ target }) {
const button = target.querySelector('button');
const video = target.querySelector('video');

button?.click();
flushSync();
video?.dispatchEvent(new Event('someevent'));
expect(handler).not.toHaveBeenCalled();
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script>
const { handler } = $props();
let show = $state(true);
</script>

<button onclick={() => show = false}>show/hide</button>
{#if show}
<video onsomeevent={handler}></video>
{/if}