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

发布于 2024-12-23 13:52:23 字数 991 浏览 2 评论 0 原文

我有一个隐藏的 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 -->

I have a hidden div containing a YouTube video in an <iframe>. When the user clicks on a link, this div becomes visible, the user should then be able to play the video.

When the user closes the panel, the video should stop playback. How can I achieve this?

Code:

<!-- 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 -->

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

淡莣 2024-12-30 13:52:23

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

唯一的调整:

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

演示: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>

The easiest way to implement this behaviour is by calling the pauseVideo and playVideo methods, when necessary. Inspired by the result of my previous answer, I have written a pluginless function to achieve the desired behaviour.

The only adjustments:

  • I have added a function, toggleVideo
  • I have added ?enablejsapi=1 to YouTube's URL, to enable the feature

Demo: http://jsfiddle.net/ZcMkt/
Code:

<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>
在风中等你 2024-12-30 13:52:23

这是 RobW 的 jQuery 回答,用于在模态窗口中隐藏/暂停 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 元素是调用 show / hide 方法的模态 div 本身 (#video-div) 和 iframe (#video-iframe) ),其视频网址为 src="" 并具有后缀 enablejsapi=1?,可实现对播放器的编程控制(例如。

有关 html 的更多信息参见 RobW 的回答。

Here's a jQuery take on RobW's answer for use hiding /pausing an iframe in a modal window:

    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":""}', '*');
        }
    }

The html elements referred to are the modal div itself (#video-div) calling the show / hide methods, and the iframe (#video-iframe) which has the video url as is src="" and has the suffix enablejsapi=1? which enables programmatic control of the player (ex. .

For more on the html see RobW's answer.

清醇 2024-12-30 13:52:23

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

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

Here is a simple jQuery snippet to pause all videos on the page based off of RobW's and DrewT's answers:

jQuery("iframe").each(function() {
  jQuery(this)[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')
});
青芜 2024-12-30 13:52:23

嘿,一个简单的方法是简单地将视频的 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>

Hey an easy way is to simply set the src of the video to nothing, so that the video will desapear while it's hidden an then set the src back to the video you want when you click on the link that opens the video.. to do that simply set an id to the youtube iframe and call the src function using that id like this:

<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>
泪是无色的血 2024-12-30 13:52:23

由于您需要在 iframe 的 src 中设置 ?enablejsapi=true 才能使用 playVideo / pauseVideo 命令="https://stackoverflow.com/questions/8667882/how-to-pause-a-youtube-player-when-hiding-the-if​​rame#answer-8668741">其他答案,它通过 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) ? "?" : "&";
      iframes[i].src += prefix + "enablejsapi=true";
    }
  }
}

...如果您在 document.ready 上调用此方法,则具有“video”类的 div 中的所有 iframe 都将具有 enablejsapi=true 添加到它们的源中,这允许 playVideo /pauseVideo 命令对它们起作用。

(注意,本示例使用 jQuery 来设置 var iframes 的那一行,但如果您不使用 jQuery,则一般方法应该与纯 Javascript 一样有效)。

Since you need to set ?enablejsapi=true in the src of the iframe before you can use the playVideo / pauseVideo commands mentioned in other answers, it might be useful to add this programmatically via Javascript (especially if, eg. you want this behaviour to apply to videos embedded by other users who have just cut and paste a YouTube embed code). In that case, something like this might be useful:

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) ? "?" : "&";
      iframes[i].src += prefix + "enablejsapi=true";
    }
  }
}

...if you call this on document.ready then all iframes in a div with a class of "video" will have enablejsapi=true added to their source, which allows the playVideo / pauseVideo commands to work on them.

(nb. this example uses jQuery for that one line that sets var iframes, but the general approach should work just as well with pure Javascript if you're not using jQuery).

樱&纷飞 2024-12-30 13:52:23

我想分享一个使用 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。希望有人会发现这也很有用。

I wanted to share a solution I came up with using jQuery that works if you have multiple YouTube videos embedded on a single page. In my case, I have defined a modal popup for each video as follows:

<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>

In this case, videoModalXX represents a unique id for the video. Then, the following function stops the video:

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

I like this approach because it keeps the video paused where you left off in case you want to go back and continue watching later. It works well for me because it's looking for the iframe inside of the video modal with a specific id. No special YouTube element ID is required. Hopefully, someone will find this useful as well.

谈下烟灰 2024-12-30 13:52:23

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

player.stopVideo()

例如有关更多详细信息,请参阅此处:http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls

You can stop the video by calling the stopVideo() method on the YouTube player instance before hiding the div e.g.

player.stopVideo()

For more details see here: http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls

情定在深秋 2024-12-30 13:52:23

RobW 的方法对我来说非常有效。对于使用 jQuery 的人来说,这是我最终使用的简化版本:

var iframe = $(video_player_div).find('iframe');

var src = $(iframe).attr('src');      

$(iframe).attr('src', '').attr('src', src);

在此示例中,“video_player”是包含 iframe 的父 div。

RobW's way worked great for me. For people using jQuery here's a simplified version that I ended up using:

var iframe = $(video_player_div).find('iframe');

var src = $(iframe).attr('src');      

$(iframe).attr('src', '').attr('src', src);

In this example "video_player" is a parent div containing the iframe.

黄昏下泛黄的笔记 2024-12-30 13:52:23

只需删除 iframe 的 src

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

just remove src of iframe

$('button.close').click(function(){
    $('iframe').attr('src','');;
});
寄与心 2024-12-30 13:52:23

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>

请注意,这适用于 localhost,并且正如 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 上查看

Rob W answer helped me figure out how to pause a video over iframe when a slider is hidden. Yet, I needed some modifications before I could get it to work. Here is snippet of my 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>

Observe that this works on localhosts and also as Rob W mentioned "enablejsapi=1" was added to the end of the video URL.

Following is my JS file:

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":""}', '*');
}; 

Also, as a simpler example, check this out on JSFiddle

内心荒芜 2024-12-30 13:52:23

这种方法需要 jQuery。首先,选择您的 iframe:

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

现在您选择该 iframe 的按钮播放/暂停并单击它,

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

我希望它会对您有所帮助。

This approach requires jQuery. First, select your iframe:

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

Now you select button play/pause of this iframe and click it

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

I hope it will help you.

音盲 2024-12-30 13:52:23

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

我有一个方法,可以形成要在 UIWebView 中加载的 HTML 字符串:

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];

您可以忽略准备好的 HTML 字符串中的样式内容。重要的方面是:

  • 使用 API 创建“YT.player”对象。在某一时刻,我只有 iFrame 标签中的视频,这阻止了我稍后使用 JS 引用“播放器”对象。
  • 我在网上看到了一些示例,其中第一个脚本标记(带有 iframe_api src 标记的标记)被省略,但我绝对需要它才能正常工作。
  • 在 API 脚本的开头创建“player”变量。我还看到一些省略了该行的例子。
  • 将 id 标记添加到 iFrame 以在 API 脚本中引用。我差点忘了那部分。
  • 将“enablejsapi=1”添加到 iFrame src 标记的末尾。这让我困惑了一段时间,因为我最初将它作为 iFrame 标签的一个属性,但它对我不起作用/不起作用。

当我需要暂停视频时,我只需运行以下命令:

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

希望有帮助!

RobW's answers here and elsewhere were very helpful, but I found my needs to be much simpler. I've answered this elsewhere, but perhaps it will be useful here also.

I have a method where I form an HTML string to be loaded in a 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];

You can ignore the styling stuff in the preparedHTML string. The important aspects are:

  • Using the API to create the "YT.player" object. At one point, I only had the video in the iFrame tag and that prevented me from referencing the "player" object later with JS.
  • I've seen a few examples on the web where the first script tag (the one with the iframe_api src tag) is omitted, but I definitely needed that to get this working.
  • Creating the "player" variable at the beginning of the API script. I have also seen some examples that have omitted that line.
  • Adding an id tag to the iFrame to be referenced in the API script. I almost forgot that part.
  • Adding "enablejsapi=1" to the end of the iFrame src tag. That hung me up for a while, as I initially had it as an attribute of the iFrame tag, which does not work/did not work for me.

When I need to pause the video, I just run this:

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

Hope that helps!

ゃ懵逼小萝莉 2024-12-30 13:52:23

效果很好

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

对于我来说,使用 YT 播放器this.youtube.player.pauseVideo();

This is working fine to me with YT player

 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();

怀里藏娇 2024-12-30 13:52:23

更简洁、优雅、安全的答案:将“?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,以确保您的消息不会被发送给任何非指定收件人。

A more concise, elegant, and secure answer: add “?enablejsapi=1” to the end of the video URL, then construct and stringify an ordinary object representing the pause command:

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

Use the Window.postMessage method to send the resulting JSON string to the embedded video document:

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

Make sure you specify the video URL for the Window.postMessage method’s targetOrigin argument to ensure that your messages won’t be sent to any unintended recipient.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文