如何在隐藏iframe时暂停YouTube播放器

How to pause a YouTube player when hiding the iframe?

本文关键字:暂停 YouTube 播放器 iframe 隐藏      更新时间:2023-09-26

我在<iframe>中有一个包含YouTube视频的隐藏div。当用户点击链接时,这个div就变得可见,用户就可以播放视频了。

当用户关闭面板时,视频应停止播放。我怎样才能做到这一点呢?

代码:

<!-- link to open popupVid -->
<p><a href="javascript:;" onClick="document.getElementById('popupVid').style.display='';">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
  <iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40" frameborder="0" allowfullscreen></iframe>
  <br /><br /> 
  <a href="javascript:;" onClick="document.getElementById('popupVid').style.display='none';">
  close
  </a>
</div><!--end of popupVid -->

实现此行为的最简单方法是在必要时调用pauseVideoplayVideo方法。受我之前答案的启发,我写了一个无插件的函数来实现预期的行为。

唯一的调整:

  • 我增加了一个功能,toggleVideo
  • 我已经添加了?enablejsapi=1到YouTube的URL,以启用功能

Demo: http://jsfiddle.net/ZcMkt/
代码:

<script>
function toggleVideo(state) {
    // if state == 'hide', hide. Else: show video
    var div = document.getElementById("popupVid");
    var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
    div.style.display = state == 'hide' ? 'none' : '';
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}
</script>
<p><a href="javascript:;" onClick="toggleVideo();">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
   <iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
   <br /><br />
   <a href="javascript:;" onClick="toggleVideo('hide');">close</a>

这是一个jQuery对RobW在模态窗口中隐藏/暂停iframe的回答:

    function toggleVideo(state) {
        if(state == 'hide'){
            $('#video-div').modal('hide');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
        }
        else {
            $('#video-div').modal('show');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
        }
    }

引用的html元素是模式div本身(#video-div)调用显示/隐藏方法,和iframe (#video-iframe)有视频url为src=",并有后缀enablejsapi=1?允许对播放器进行编程控制(例如

)

有关html的更多信息,请参阅RobW的回答。

下面是一个简单的jQuery代码片段,用于根据RobW和DrewT的答案暂停页面上的所有视频:

jQuery("iframe").each(function() {
  jQuery(this)[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')
});

嘿,一个简单的方法是简单地将视频的src设置为无,使视频在隐藏时消失,然后将src设置为您想要的视频,当您点击打开视频的链接时。要做到这一点,只需为YouTube iframe设置一个id并使用该id调用SRC函数,如下所示:

<script type="text/javascript">
function deleteVideo()
{
document.getElementById('VideoPlayer').src='';
}
function LoadVideo()
{
document.getElementById('VideoPlayer').src='http://www.youtube.com/embed/WHAT,EVER,YOUTUBE,VIDEO,YOU,WHANT';
}
</script>
<body>
<p onclick="LoadVideo()">LOAD VIDEO</P>
<p onclick="deleteVideo()">CLOSE</P>
<iframe id="VideoPlayer" width="853" height="480" src="http://www.youtube.com/WHAT,EVER,YOUTUBE,VIDEO,YOU,HAVE" frameborder="0" allowfullscreen></iframe>
</boby>

因为您需要在iframe的src中设置?enablejsapi=true,然后才能使用其他答案中提到的playVideo/pauseVideo命令,通过Javascript以编程方式添加这可能是有用的(特别是如果,例如:你希望这种行为适用于其他用户嵌入的视频谁只是剪切和粘贴YouTube嵌入代码)。在这种情况下,像这样的东西可能很有用:

function initVideos() {
  // Find all video iframes on the page:
  var iframes = $(".video").find("iframe");
  // For each of them:
  for (var i = 0; i < iframes.length; i++) {
    // If "enablejsapi" is not set on the iframe's src, set it:
    if (iframes[i].src.indexOf("enablejsapi") === -1) {
      // ...check whether there is already a query string or not:
      // (ie. whether to prefix "enablejsapi" with a "?" or an "&")
      var prefix = (iframes[i].src.indexOf("?") === -1) ? "?" : "&amp;";
      iframes[i].src += prefix + "enablejsapi=true";
    }
  }
}

…如果你在document.ready上调用这个,那么div中带有"video"类的所有iframe将有enablejsapi=true添加到它们的源,这允许playVideo/pauseVideo命令对它们工作。

(nb。本例在设置var iframes的那一行中使用了jQuery,但是如果您不使用jQuery,那么使用纯Javascript的一般方法应该也能正常工作)。

我想分享一个使用jQuery的解决方案,如果你有多个YouTube视频嵌入在一个页面上。在我的例子中,我为每个视频定义了一个模态弹出框,如下所示:

<div id="videoModalXX">
...
    <button onclick="stopVideo(videoID);" type="button" class="close"></button>
    ...
    <iframe width="90%" height="400" src="//www.youtube-nocookie.com/embed/video_id?rel=0&enablejsapi=1&version=3" frameborder="0" allowfullscreen></iframe>
...
</div>

在本例中,videoModalXX表示视频的唯一id。然后,以下功能停止视频:

function stopVideo(id)
{
    $("#videoModal" + id + " iframe")[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}

我喜欢这种方法,因为它使视频在你离开的地方暂停,以防你稍后想回去继续观看。它对我来说很好,因为它正在寻找具有特定id的视频模态内部的iframe。不需要特殊的YouTube元素ID。希望有人也会觉得这很有用。

您可以在隐藏div之前调用YouTube播放器实例上的stopVideo()方法来停止视频,例如

player.stopVideo()

更多细节见这里:http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls

RobW的方式对我来说很好。对于使用jQuery的人,这里是我最终使用的简化版本:

var iframe = $(video_player_div).find('iframe');
var src = $(iframe).attr('src');      
$(iframe).attr('src', '').attr('src', src);

在这个例子中"video_player"是包含iframe的父div。

just remove SRC of iframe

$('button.close').click(function(){
    $('iframe').attr('src','');;
});

Rob W的回答帮助我弄清楚了当滑动条被隐藏时如何在iframe上暂停视频。然而,在我能让它工作之前,我需要一些修改。这是我的html代码片段:

<div class="flexslider" style="height: 330px;">
  <ul class="slides">
    <li class="post-64"><img src="http://localhost/.../Banner_image.jpg"></li>
    <li class="post-65><img  src="http://localhost/..../banner_image_2.jpg "></li>
    <li class="post-67 ">
        <div class="fluid-width-video-wrapper ">
            <iframe frameborder="0 " allowfullscreen=" " src="//www.youtube.com/embed/video-ID?enablejsapi=1 " id="fitvid831673 "></iframe>
        </div>
    </li>
  </ul>
</div>

观察这在localhosts上工作,并且正如Rob W提到的"enablejsapi=1"被添加到视频URL的末尾。

以下是我的JS文件:
jQuery(document).ready(function($){
    jQuery(".flexslider").click(function (e) {
        setTimeout(checkiframe, 1000); //Checking the DOM if iframe is hidden. Timer is used to wait for 1 second before checking the DOM if its updated
    });
});
function checkiframe(){
    var iframe_flag =jQuery("iframe").is(":visible"); //Flagging if iFrame is Visible
    console.log(iframe_flag);
    var tooglePlay=0;
    if (iframe_flag) {                                //If Visible then AutoPlaying the Video
        tooglePlay=1;
        setTimeout(toogleVideo, 1000);                //Also using timeout here
    }
    if (!iframe_flag) {     
        tooglePlay =0;
        setTimeout(toogleVideo('hide'), 1000);  
    }   
}
function toogleVideo(state) {
    var div = document.getElementsByTagName("iframe")[0].contentWindow;
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    div.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}; 

还有一个更简单的例子,可以在JSFiddle上查看

这个方法需要jQuery。首先,选择iframe:

var yourIframe = $('iframe#yourId');
//yourId or something to select your iframe.

现在你选择这个iframe的按钮播放/暂停,然后点击它

$('button.ytp-play-button.ytp-button', yourIframe).click();

希望对你有帮助。

RobW在这里和其他地方的回答非常有帮助,但我发现我的需求要简单得多。我已经在其他地方回答过这个问题,但也许它在这里也会有用。

我有一个方法,我形成一个HTML字符串加载在UIWebView:

NSString *urlString = [NSString stringWithFormat:@"https://www.youtube.com/embed/%@",videoID];
preparedHTML = [NSString stringWithFormat:@"<html><body style='background:none; text-align:center;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>var player; function onYouTubeIframeAPIReady(){player=new YT.Player('player')}</script><iframe id='player' class='youtube-player' type='text/html' width='%f' height='%f' src='%@?rel=0&showinfo=0&enablejsapi=1' style='text-align:center; border: 6px solid; border-radius:5px; background-color:transparent;' rel=nofollow allowfullscreen></iframe></body></html>", 628.0f, 352.0f, urlString];

你可以忽略preparedHTML字符串中的样式内容。重要的方面是:

  • 使用API创建"YT"。球员"对象。有一次,我在iFrame标签中只有视频,这阻止了我稍后在JS中引用"player"对象。
  • 我在web上看到了几个例子,其中第一个脚本标签(与iframe_api src标签的一个)被省略,但我绝对需要得到这个工作。
  • 在API脚本的开头创建"player"变量。我也看到一些例子省略了这一行。
  • 为iFrame添加一个id标签,以便在API脚本中引用。我差点忘了这部分。
  • 在iFrame src标签的末尾添加"enablejsapi=1"。这让我挂了一段时间,因为我最初把它作为iFrame标签的一个属性,它不工作/不为我工作。

当我需要暂停视频时,我只需运行这个:

[webView stringByEvaluatingJavaScriptFromString:@"player.pauseVideo();"];

希望有帮助!

这对我来说很好。

 createPlayer(): void {
  return new window['YT'].Player(this.youtube.playerId, {
  height: this.youtube.playerHeight,
  width: this.youtube.playerWidth,
  playerVars: {
    rel: 0,
    showinfo: 0
  }
});
}

this.youtube.player.pauseVideo();

一个更简洁、优雅、安全的答案:add " ?enablejsapi=1"到视频URL的末尾,然后构造并字符串化一个表示暂停命令的普通对象:

const YouTube_pause_video_command_JSON = JSON.stringify(Object.create(null, {
    "event": {
        "value": "command",
        "enumerable": true
    },
    "func": {
        "value": "pauseVideo",
        "enumerable": true
    }
}));

使用Window.postMessage方法将结果JSON字符串发送到嵌入的视频文档:

// |iframe_element| is defined elsewhere.
const video_URL = iframe_element.getAttributeNS(null, "src");
iframe_element.contentWindow.postMessage(YouTube_pause_video_command_JSON, video_URL);

确保您为Window.postMessage方法的targetOrigin参数指定了视频URL,以确保您的消息不会发送给任何意想不到的收件人。