Programing

iframe을 숨길 때 YouTube 플레이어를 일시 중지하는 방법은 무엇입니까?

lottogame 2020. 9. 17. 18:49
반응형

iframe을 숨길 때 YouTube 플레이어를 일시 중지하는 방법은 무엇입니까?


.NET 파일에 YouTube 동영상이 포함 된 숨겨진 div가 <iframe>있습니다. 사용자가 링크를 클릭하면이 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에 추가 했습니다.

데모 : 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>

다음은 모달 창에서 iframe을 숨기거나 일시 중지하는 데 사용되는 RobW의 답변에 대한 jQuery입니다.

    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)와 비디오 URL이 src = ""이고 접미사 enablejsapi = 1 이있는 iframe (# video-iframe)입니다. ? 플레이어를 프로그래밍 방식으로 제어 할 수 있습니다 (예 :.

html에 대한 자세한 내용은 RobW의 답변을 참조하십시오.


다음은 RobW 및 DrewT의 답변을 기반으로 페이지의 모든 비디오를 일시 중지하는 간단한 jQuery 스 니펫입니다.

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>

다른 답변에 언급 된 / 명령을 ?enablejsapi=true사용하기 전에 iframe의 src에 설정해야하므로 Javascript를 통해 프로그래밍 방식으로 추가하는 것이 유용 할 수 있습니다 (특히이 동작을 다른 사람이 삽입 한 비디오에 적용하려는 경우) YouTube 소스 코드를 잘라내어 붙여 넣은 사용자). 이 경우 다음과 같은 것이 유용 할 수 있습니다.playVideopauseVideo

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";
    }
  }
}

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


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


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.


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.


just remove src of iframe

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

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


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.


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!


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


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.

참고URL : https://stackoverflow.com/questions/8667882/how-to-pause-a-youtube-player-when-hiding-the-iframe

반응형