Move your custom video player into Document Picture-in-Picture (controls included)

2026-11-26来源 dev.toEnglish

TL;DR

video.requestPictureInPicture() only takes the <video>, so your custom controls vanish. documentPictureInPicture.requestWindow() opens an always-on-top window you fill with your own DOM. We'll move a live player (hls.js included) into it without interrupting playback, copy styles, fix keyboard shortcuts, move it back on close, and fall back to classic PiP where Document PiP doesn't exist. Tested in Chromium 158 with hls.js 1.7.4.

Browser support (Nov 2026)

Browser Document PiP Notes
Chrome / Edge desktop ✅ 116+ disallowReturnToOpener 124+, preferInitialWindowPlacement 130+
Firefox desktop ✅ 151+ shipped May 2026
Safari ❌ use classic requestPictureInPicture()
Chrome Android ❌ use classic API

Sources: Chrome for Developers, Firefox 151 release notes.

1. The starting player 🎥

A normal custom player: one container, a video, a control bar.

<!-- index.html --> <button id="pipBtn">Pop out</button> <div id="slot"> <div class="player" id="player"> <video id="v" muted playsinline></video> <div class="controls"> <button class="play">Pause</button> <button class="fs">Fullscreen</button> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/hls.js@1.7.4/dist/hls.min.js"></script> <script type="module" src="./player.js"></script> 
/* player.css */ .player { position: relative; width: 640px; } .controls { background: rgb(20, 20, 20); color: white; } 

2. Open the window and move the player

The whole trick is append(). You're not cloning anything; the same node moves to the new document.

// pip.js export async function openDocPip(player) { const pip = await documentPictureInPicture.requestWindow({ width: 640, height: 400 }); copyStyles(pip); // step 3 pip.document.body.append(player); // move, don't clone pip.addEventListener('pagehide', () => { document.getElementById('slot').append(player); // move it home on close }); return pip; } 

Does playback survive the move? I ran the finished demo from this post (all of steps 2 to 6, fMP4 HLS through hls.js) in Chromium 158 with a Playwright script that logs currentTime, presses k inside the PiP window, closes it, then presses k in the page:

$ node test-move.js before 1.22 paused=false in pip 1.81 paused=false inPipDoc= true controls bg rgb(20, 20, 20) fs button none after k in pip 1.83 paused=true after k again 2.83 paused=false back home 3.34 paused=false inMain= true k in main doc 3.35 paused=true 

No reset and no pause when moving in either direction; the hls.js instance kept feeding the same element after it changed documents. (I also ran the move with a plain progressive MP4: same result.) The keyboard lines only work because of step 4.

⚠️ Note: requestWindow() must be called from a user gesture (a click handler), or the promise rejects. You can't open it automatically on scroll.

3. Copy your styles

The PiP document starts empty. Before copying, my .controls background computed to rgba(0, 0, 0, 0); after, rgb(20, 20, 20). This is the pattern from Chrome's docs:

// pip.js function copyStyles(pip) { for (const sheet of document.styleSheets) { try { const css = [...sheet.cssRules].map(r => r.cssText).join(''); const style = document.createElement('style'); style.textContent = css; pip.document.head.append(style); } catch { // cross-origin sheet: cssRules throws, so link it instead const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = sheet.href; pip.document.head.append(link); } } } 

💡 Tip: if you use CSS-in-JS that injects styles at runtime, styles added after you open the window won't be copied. Open the window after your player has rendered once.

4. Stop reaching for document 🛠️

This is where most players break. After the move:

document.querySelector('.play'); // null: the button is in the other document document.addEventListener('keydown', f); // never fires while the PiP window has focus 

I confirmed both: a key pressed in the PiP window reached a listener on pip.document and not one on the page's document. Click handlers bound directly on buttons kept working, since the nodes carry their listeners.

Refactor the player to resolve everything from its own root:

// player.js export function mountPlayer(root) { const video = root.querySelector('video'); const playBtn = root.querySelector('.play'); playBtn.onclick = () => (video.paused ? video.play() : video.pause()); const onKey = (e) => { if (e.key === 'k' || e.key === ' ') { e.preventDefault(); playBtn.click(); } }; let keyDoc = null; function bindKeys() { keyDoc?.removeEventListener('keydown', onKey); keyDoc = root.ownerDocument; // whichever document the player is in now keyDoc.addEventListener('keydown', onKey); } bindKeys(); return { video, rebind: bindKeys }; } 

Call rebind() after every move:

// main.js import { mountPlayer } from './player.js'; import { openDocPip } from './pip.js'; const root = document.getElementById('player'); const player = mountPlayer(root); const hls = new Hls(); hls.loadSource('/hls_long/index.m3u8'); hls.attachMedia(player.video); document.getElementById('pipBtn').onclick = async () => { if ('documentPictureInPicture' in window) { const pip = await openDocPip(root); player.rebind(); root.classList.add('in-pip'); pip.addEventListener('pagehide', () => { root.classList.remove('in-pip'); queueMicrotask(player.rebind); }); } else if (document.pictureInPictureEnabled) { await player.video.requestPictureInPicture(); // classic fallback: video only } }; 

5. Watch out for cross-window instanceof

The PiP window has its own globals. From my test:

v instanceof HTMLVideoElement // true (node created in the page) pip.document.createElement('div') instanceof HTMLDivElement // false pip.document.createElement('div') instanceof pip.HTMLDivElement // true 

If your player or UI library creates nodes inside the PiP document and type-checks them, use el.nodeName === 'DIV' or el.ownerDocument.defaultView.HTMLDivElement.

6. Hide what doesn't work in PiP

pip.document.fullscreenEnabled was false in my run, so a fullscreen button is dead weight. Chrome documents a media query for this (Chrome 123+):

/* player.css */ @media all and (display-mode: picture-in-picture) { .fs { display: none; } } /* backup that doesn't depend on the media query */ .player.in-pip .fs { display: none; } 

⚠️ Note: in headless Chromium the display-mode: picture-in-picture query did not match inside the PiP window, which is why the .in-pip class is there. Check the media query in a real headed browser before relying on it alone.

7. Close the window from your code

The viewer isn't the only one who should close the window. Two cases I'd handle from day one:

  • The video ends. A floating window showing a finished video is clutter.
  • Your SPA unmounts the player. If a route change destroys the player component while it's floating, you're left with an always-on-top window holding a dead element (and, with hls.js, possibly a leaked instance).

documentPictureInPicture.window returns the open window or null, so closing is one line. Closing fires the same pagehide handler from step 2, which moves the player home:

// main.js (continued) // window.* so this doesn't throw a ReferenceError in Safari, where the API doesn't exist const closeDocPip = () => window.documentPictureInPicture?.window?.close(); player.video.addEventListener('ended', closeDocPip); // in your framework's unmount / cleanup hook: export function destroyPlayer() { closeDocPip(); hls.destroy(); } 

Checked in the same Chromium run: after seeking to half a second before the end, the window closed on ended and the player was back in #slot:

$ node test-close.js open? true after ended { open: false, playerHome: true } 

Rules the API enforces

  • One PiP window per tab. A second requestWindow() closes the first.
  • The window can't be navigated, and the site can't set its position.
  • It closes when the opener tab closes.
  • width and height go together; pass both or neither.
  • Optional: disallowReturnToOpener: true (Chrome 124+) hides the back-to-tab button; preferInitialWindowPlacement: true (Chrome 130+) opens at the default spot instead of the viewer's last one.

Things to know

  • Tested: headless Chromium 158.0.8127.36 via Playwright, hls.js 1.7.4, progressive MP4 and fMP4 HLS.
  • Not tested: Firefox (support is from Mozilla's release notes), Safari fallback on a real device, and window sizing. Headless ignored my requested size and didn't enforce the user-gesture rule, so those behaviors come from the docs.

What's next

  • Put captions and a chapter list in the PiP window. That's where Document PiP beats the classic API for course and long-form content.
  • For live streams, try moving a chat panel in alongside the video. Same pattern, more DOM.

原文:https://www.a8q9.cn/en/article/move-your-custom-video-player-into-document-picture-in-picture-controls-included-84c639.html

相关文章