Skip to content

Build your personal knowledge base with Trilium Notes

text editor/link preview: stop the videos playing in background for cached widgets

Adorian Doran43c14ee4c8be
diff --git a/apps/client/src/services/media_playback.spec.ts b/apps/client/src/services/media_playback.spec.ts
new file mode 100644
index 0000000000..b9a161b094
--- /dev/null
+++ b/apps/client/src/services/media_playback.spec.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { stopBackgroundMedia } from "./media_playback.js";
+
+/** Tracks assignments to `iframe.src`, returning a getter for the count. */
+function trackSrc(iframe: HTMLIFrameElement) {
+ let value = iframe.getAttribute("src") ?? "";
+ let setCount = 0;
+ Object.defineProperty(iframe, "src", {
+ get: () => value,
+ set: (v: string) => {
+ value = v;
+ setCount++;
+ },
+ configurable: true
+ });
+ return () => setCount;
+}
+
+describe("stopBackgroundMedia", () => {
+ it("pauses HTML5 media and reloads only known video-embed iframes", () => {
+ const container = document.createElement("div");
+ container.innerHTML = `
+ <video></video>
+ <audio></audio>
+ <figure class="media"><div data-oembed-url="x"><iframe src="https://www.youtube.com/embed/a"></iframe></div></figure>
+ <div class="link-embed-video"><iframe src="https://www.youtube-nocookie.com/embed/b"></iframe></div>
+ <iframe class="pdf" src="blob:pdf"></iframe>
+ `;
+
+ const video = container.querySelector("video")!;
+ const audio = container.querySelector("audio")!;
+ video.pause = vi.fn();
+ audio.pause = vi.fn();
+
+ const mediaIframe = container.querySelector("figure.media iframe") as HTMLIFrameElement;
+ const linkEmbedIframe = container.querySelector(".link-embed-video iframe") as HTMLIFrameElement;
+ const pdfIframe = container.querySelector("iframe.pdf") as HTMLIFrameElement;
+ const mediaSets = trackSrc(mediaIframe);
+ const linkSets = trackSrc(linkEmbedIframe);
+ const pdfSets = trackSrc(pdfIframe);
+
+ stopBackgroundMedia(container);
+
+ expect(video.pause).toHaveBeenCalledTimes(1);
+ expect(audio.pause).toHaveBeenCalledTimes(1);
+ // Embed iframes reloaded (src reassigned), unrelated PDF iframe untouched.
+ expect(mediaSets()).toBe(1);
+ expect(linkSets()).toBe(1);
+ expect(pdfSets()).toBe(0);
+ });
+
+ it("is a no-op for null/empty containers", () => {
+ expect(() => stopBackgroundMedia(null)).not.toThrow();
+ expect(() => stopBackgroundMedia(document.createElement("div"))).not.toThrow();
+ });
+});
diff --git a/apps/client/src/services/media_playback.ts b/apps/client/src/services/media_playback.ts
new file mode 100644
index 0000000000..94dd5386f8
--- /dev/null
+++ b/apps/client/src/services/media_playback.ts
@@ -0,0 +1,32 @@
+/**
+ * Stops audio/video still playing inside a container that is about to be hidden
+ * but kept mounted (e.g. the note-type widget cache in `NoteDetail`, which only
+ * toggles a `hidden-ext` class instead of unmounting). A `display:none` element
+ * keeps its media playing, so switching a read-only note with a playing video to
+ * editable mode would otherwise leave the video running in the background.
+ *
+ * - HTML5 `<video>` / `<audio>` are paused directly.
+ * - Cross-origin embeds (YouTube, Vimeo, …) expose no pause API to the host page,
+ * so the iframe is reloaded by reassigning its `src`. This tears down the
+ * player and stops the audio; because the embeds don't autoplay, the reloaded
+ * iframe simply shows its thumbnail again when the container is shown later.
+ *
+ * Scoped to the known video-embed containers — Trilium's Link Preview
+ * (`.link-embed-video`) and `figure.media` — so unrelated iframes (PDFs,
+ * web-view notes, included notes) are left untouched and don't lose their state.
+ */
+export function stopBackgroundMedia(container: HTMLElement | null | undefined) {
+ if (!container) return;
+
+ for (const el of container.querySelectorAll<HTMLMediaElement>("video, audio")) {
+ el.pause();
+ }
+
+ for (const iframe of container.querySelectorAll<HTMLIFrameElement>("figure.media iframe, .link-embed-video iframe")) {
+ const src = iframe.src;
+ if (src) {
+ // Reassigning src (even to the same value) reloads the frame.
+ iframe.src = src;
+ }
+ }
+}
diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsx
index 13022e80a3..973fa062e9 100644
--- a/apps/client/src/widgets/NoteDetail.tsx
+++ b/apps/client/src/widgets/NoteDetail.tsx
@@ -11,6 +11,7 @@ import type { PrintReport } from "../print";
import attributes from "../services/attributes";
import dialog from "../services/dialog";
import { t } from "../services/i18n";
+import { stopBackgroundMedia } from "../services/media_playback";
import protected_session_holder from "../services/protected_session_holder";
import toast from "../services/toast.js";
import { isElectron, isMobile } from "../services/utils";
@@ -244,6 +245,7 @@ function FixedTree({ noteContext }: { noteContext: NoteContext }) {
*/
function NoteDetailWrapper({ Element, type, isVisible, isFullHeight, props }: { Element: (props: TypeWidgetProps) => VNode, type: ExtendedNoteType, isVisible: boolean, isFullHeight: boolean, props: TypeWidgetProps }) {
const [ cachedProps, setCachedProps ] = useState(props);
+ const wrapperRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (isVisible) {
@@ -252,9 +254,19 @@ function NoteDetailWrapper({ Element, type, isVisible, isFullHeight, props }: {
// When not visible, keep the old props to avoid re-rendering in the background.
}, [ props, isVisible ]);
+ // This widget stays mounted (just hidden) when the user switches note type —
+ // e.g. read-only ↔ editable text. A hidden but still-mounted embedded player
+ // keeps playing audio/video in the background, so stop it whenever it's hidden.
+ useEffect(() => {
+ if (!isVisible) {
+ stopBackgroundMedia(wrapperRef.current);
+ }
+ }, [ isVisible ]);
+
const typeMapping = TYPE_MAPPINGS[type];
return (
<div
+ ref={wrapperRef}
className={`${typeMapping.className} ${typeMapping.printable ? "note-detail-printable" : ""} ${isVisible ? "visible" : "hidden-ext"}`}
style={{
height: isFullHeight ? "100%" : ""
diff --git a/apps/desktop/src/services/embed_referer.ts b/apps/desktop/src/services/embed_referer.ts
index 9d46c3b2ee..47d8b57dd9 100644
--- a/apps/desktop/src/services/embed_referer.ts
+++ b/apps/desktop/src/services/embed_referer.ts
@@ -9,9 +9,9 @@ import electron, { type Session } from "electron";
* require a valid Referer for embeds.
*
* The browser/server client works because its real origin (`http://localhost:<port>`)
- * is sent as the Referer; we replicate that for the desktop app. This fixes both
- * CKEditor's MediaEmbed and Trilium's own link embeds, since both point the
- * iframe at these same provider URLs.
+ * is sent as the Referer; we replicate that for the desktop app. This fixes
+ * Trilium's link embeds (and any other embedded YouTube/Vimeo iframe), since
+ * they point the iframe at these same provider URLs.
*
* Add new entries here if another embed provider shows the same failure.
*/