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

模态框中iframe YouTube视频重复加载且需保留暂停功能问题

问题:模态框中YouTube iframe视频重复加载且无法正常暂停

我在开发带模态框的页面,模态框里同时有iframe嵌入的YouTube视频和原生video标签视频。原生视频正常,但点击含iframe的模态框时,视频会加载两次。排查后发现是这段代码导致重复加载:

element.src = elementSrc;

但删掉这段代码,关闭模态框或点击外部时,视频又没法暂停。


解决思路

不要通过重置iframe的src来暂停视频,改用YouTube的postMessage控制指令,既能暂停视频,又不会触发重复加载。

具体步骤

  • 修改iframe的src,添加enablejsapi=1参数,允许通过JS控制视频
  • 在pauseVideo函数里,给iframe发送pause指令的postMessage
  • 保留原生video的暂停逻辑不变

修改后的代码

JavaScript代码

document.addEventListener('DOMContentLoaded', function() {
    function pauseVideo(element) {
        if (element.tagName === 'VIDEO') {
            element.pause();
        } else if (element.tagName === 'IFRAME') {
            // 给YouTube iframe发送暂停指令
            element.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
        }
    }

    var modals = document.querySelectorAll('.test--img-gallery');

    modals.forEach(function(modal) {
        var closeButton = modal.querySelector('[data-close-modal]');
        var video = modal.querySelector('video');
        var iframe = modal.querySelector('iframe');

        closeButton.addEventListener('click', function() {
            pauseVideo(video || iframe);
        });

        modal.addEventListener('click', function(event) {
            if (event.target === modal) {
                pauseVideo(video || iframe);
            }
        });

        document.addEventListener('click', function(event) {
            if (!modal.contains(event.target)) {
                pauseVideo(video || iframe);
            }
        });
    });
});

HTML代码(修改iframe的src)

<div class="usa-modal usa-modal--lg test-modal--img-gallery" id="modal--exhibit-1" aria-modal="true" aria-labelledby="modal--exhibit-1-heading" aria-describedby="modal--exhibit-1-description">
<div class="usa-modal__content">
<div class="usa-modal__main">
<h2 class="usa-modal__heading" id="modal--exhibit-2-heading">dfdf</h2>

<!-- 添加enablejsapi=1参数,开启JS控制权限 -->
<iframe width="860" height="415" src="https://www.youtube-nocookie.com/embed/dfdfdff?enablejsapi=1" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div>

<button type="button" class="usa-button usa-modal__close" aria-label="Close this window" data-close-modal><svg class="usa-icon" aria-hidden="true" focusable="false" role="img"><use xlink:href="/images/c-clamp-images/sprite.svg#close"></use></svg></button></div>
</div>
</div>

额外说明

  • 如果YouTube链接已有其他参数,用&enablejsapi=1拼接(例如src="xxx?param1=value&enablejsapi=1")
  • 可以把postMessage的目标域名从*改为https://www.youtube-nocookie.com,提升页面安全性

内容的提问来源于stack exchange,提问作者newuser

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:57:40