You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel站点中实现播放新视频时自动停止其他YouTube嵌入视频的技术求助

Fix: Auto-Stop Other YouTube Videos When One Plays in Laravel

Hey there! Let's get that video playback conflict sorted out for your Laravel site. The issue with your current code is that it only sends a stopVideo command once when the page loads—there's no logic to listen for when a video starts playing and trigger the stop for other videos afterward. Here's a step-by-step fix:

Step 1: Update Your Iframe Markup

First, you need to add the enablejsapi=1 parameter to your YouTube embed URL (this enables the YouTube JavaScript API, which is required for controlling videos via postMessage). Also, give each iframe a unique ID to avoid conflicts (using your post's ID is perfect here):

<iframe id="youtube_player_{{$post->id}}" class="yt_player_iframe" width="100%" height="350" 
        src="https://www.youtube.com/embed/{{$post->video_link}}?enablejsapi=1" 
        title="YouTube video player" frameborder="0" 
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
        allowfullscreen></iframe>

Step 2: Add the JavaScript Logic

This code will listen for when any YouTube video starts playing, then automatically stop all other embedded videos on the page:

// Listen for messages from YouTube iframes
window.addEventListener('message', function(event) {
    // Only process messages from YouTube's domain for security
    if (event.origin !== 'https://www.youtube.com') return;

    try {
        const messageData = JSON.parse(event.data);
        
        // Check if the video just started playing (state code 1 = playing)
        if (messageData.event === 'onStateChange' && messageData.data === 1) {
            // Find the iframe that's currently playing
            const activeIframe = document.querySelector(`iframe[src*="${event.source.location.pathname}"]`);
            
            // Stop all other YouTube iframes
            document.querySelectorAll('.yt_player_iframe').forEach(function(iframe) {
                if (iframe !== activeIframe) {
                    iframe.contentWindow.postMessage(
                        '{"event":"command","func":"stopVideo","args":""}',
                        'https://www.youtube.com'
                    );
                }
            });
        }
    } catch (err) {
        // Ignore any malformed messages from the iframe
        return;
    }
});

// Initialize event listeners for all YouTube iframes
document.querySelectorAll('.yt_player_iframe').forEach(function(iframe) {
    iframe.contentWindow.postMessage(
        '{"event":"command","func":"addEventListener","args":["onStateChange"]}',
        'https://www.youtube.com'
    );
});

Why This Works

  • The enablejsapi=1 parameter lets the iframe communicate with your page's JavaScript.
  • We listen for the onStateChange event from YouTube—when a video switches to "playing" (state 1), we trigger the stop command for all other iframes.
  • Using https://www.youtube.com as the target origin instead of * is more secure and avoids browser restrictions on cross-origin messages.

内容的提问来源于stack exchange,提问作者H.M. Mohiuddin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 13:34:06