Vimeo API not detecting play event - javascript

I'm trying to detect a click of the play button using hte vimeo js api. Here is my code:
html:
<iframe id="video" src="https://player.vimeo.com/video/21777784?api=1" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
and the JS:
var iframe = document.getElementById('video');
var player = $f(iframe);
player.on('play', function() {
console.log('played the video!');
});
At the moment i'm not getting anything logged in the console. I do have another function using the Vimeo API later down in the DOM which seems to be working fine:
jQuery("body").on("click",".watch-vid-cta",function(){
player.api("play");
});
I got the code straight form their API so not sure what I could be doing wrong:
https://github.com/vimeo/player.js

It seems that there are two issues here.
First : vimeo has released it's new api (2016) recently, and it's not compatible with the former one. The code you provided is a mix of the two api, player.api("play") is the old syntax, while the new synax is player.play().
As you second function is working, I would assume that you're using the old api (known as froogaloops). The github page of vimeo contains all the explanation you may nedd to migrate and it's super easy.
Second : within the new api, it seems that you mixed the event listener player.on('play', function() {} whitch do something when the player is played and the play() method, use to play the player.
With the new api your code might look like this :
html :
<button type="button" id="playButton">Play</button>
then you need to include the api in your page
<script src="https://player.vimeo.com/api/player.js"></script>
and finally your js :
var iframe = document.querySelector('iframe');
var player = new Vimeo.Player(iframe);
function vimeoPlay(){
player.play().then(function(){
})
.catch(function(error) {
switch (error.name) {
case 'PasswordError':
break;
case 'PrivacyError':
break;
default:
break;
}
});
}
document.getElementById("playButton").onclick = function (){vimeoPlay()}
Here the player.play() method has a promise .then(function{}), this enable you to do something once the player is played, and thus only once every time you call the vimeoPlay function, by clicking on the button in this case.
Hope this helps
EDIT :
regarding your comment, I belive that you are facing the first issue.
If your second function, which contains player.api("play") works, it probably means that you are using the old api (froogaloops) as with the new api (2016) it would be player.play().
If so, you can't expect player.on('play', function() {console.log('played the video!');}); to work as it is the syntax of the new api.
You should double check which version of the api you are using, the link to the old and the new ones are respectively :
<script src="https://f.vimeocdn.com/js/froogaloop2.min.js"></script>
//versus
<script src="https://player.vimeo.com/api/player.js"></script>
If your wish is indeed to listen to a play event then you may try this with the new api
<iframe id="video" src="https://player.vimeo.com/video/21777784"></iframe>
<script src="https://player.vimeo.com/api/player.js"></script>
<script type="text/javascript">
var iframe = document.querySelector('iframe');
var player = new Vimeo.Player(iframe);
player.on('play', function() {
console.log('played the video!');
});
</script>
I highligh your attention toward the difference between the way you embed the video and the way I do, you shouldn't add ?api=1 with the new api :
<iframe id="video" src="https://player.vimeo.com/video/21777784?api=1"></iframe>
//versus
<iframe id="video" src="https://player.vimeo.com/video/21777784"></iframe>
and toward the difference between the way you set your variables and I do:
var iframe = document.getElementById('video');
var player = $f(iframe);
//versus
var iframe = document.querySelector('iframe');
var player = new Vimeo.Player(iframe);
If you have multiple vimeo video on the same page you may of couses attribute an id to your vimeo iframes, for instance vimeoPlayer1 and vimeoPlayer2 and write
<iframe id="vimeoPlayer1" src="https://player.vimeo.com/video/21777784"></iframe>
<iframe id="vimeoPlayer2" src="https://player.vimeo.com/video/21777784"></iframe>
var vPlayer1 = document.getElementById("vimeoPlayer1");
var player1 = new Vimeo.Player(vPlayer1)
var vPlayer2 = document.getElementById("vimeoPlayer2");
var player2 = new Vimeo.Player(vPlayer2)
Finally you may upgrade you second function by replacing player.api("play") by player.play() (but I'm not confortable with jQuery if there is something else going on here):

Related

auto-advance to next page when iframe video ends in Qualtrics

I am trying to embed a vimeo video using iframe in my Qualtrics survey. When this video ends, I want to automatically advance to the next page (i.e., automatically press the "next button"). Before using vimeo, my videos were stored on dropbox and I used the following code for this (the url is not the real one):
<video autoplay="" id="video1" height="580" width="740"><source src="https://dl.dropboxusercontent.com/u/6339921/att/fam.mp4" type="video/mp4"></video>
Qualtrics.SurveyEngine.addOnload(function() {
that = this;
document.getElementById('video1').addEventListener('ended',myHandler,false);
function myHandler(e) {
if(!e) {
e = window.event;
}
that.clickNextButton();
}
});
However, it seems that I have to use iframe with vimeo, but I am unable to make the auto-advance work (the video will play but the page will not advance). Maybe it is because I am assigning the "ID" the wrong way. Here is the code:
<iframe id="player1" src="https://player.vimeo.com/video/20708824?autoplay=1api=1&player_id=player1&title=0&byline=0&portrait=0&background=1&mute=0&loop=0" width="600" height="400" frameborder="0"></iframe>
Qualtrics.SurveyEngine.addOnload(function() {
that = this;
var idPlayer = new Vimeo.Player('player1');
document.getElementByID('player1').addEventListener('ended',myHandler,false);
function myHandler(e) {
if(!e) { e = window.event; }
that.clickNextButton();
}
});
I am looking for a) an option to fix the iframe code, or b) an option to embed a vimeo video using the old code that I had used with dropbox videos.
Thanks so much and I apologize if this all sounds naive, I am not a programmer :-(
You can't add an event listener to an iframe from a different domain. It is called cross-domain scripting and for security reasons isn't allowed by the browser.
You have to use postMessage. There is a JavaScript class already written, but you would have figure out how to integrate it into Qualtrics:
https://github.com/vimeo/player.js

The player element passed isn’t a Vimeo embed. Player JS

I'm using Vimeo player's JavaScript API for starting a video when a user clicks on the specific button on the site.
Here's the embedded code:
<iframe id="vimeo-player" src="<?php the_sub_field('slide_video'); ?>?title=0&byline=0&portrait=0" width="1880" height="1058" frameborder="0" ></iframe>
Here's the JavaScript:
var iframe = document.querySelector('#vimeo-player');
var player = new Vimeo.Player(iframe);
$('.slide-area__slides__video svg').click(function(){
$(this).hide();
$(this).closest('.item').find('img').hide();
$(this).siblings('iframe').show();
player.play();
});
player.on('ended', function(data) {
$('.slide-area__slides__video svg').show();
$('.slide-area__slides__video iframe').hide();
$('.slider-area__slides .item img').show();
});
It works perfectly in Chrome, but in every other browser, it just keeps throwing the error:
The player element passed isn’t a Vimeo embed.
Has anyone encountered this before? It's quite frustrating.
Looking at player.js, it seems that the error displays when:
if (element.nodeName === 'IFRAME' && !isVimeoUrl(element.getAttribute('src') || '') {...}
Make sure the_sub_field('slide_video') outputs a valid Vimeo URL.

Auto-play youtube and soundcloud embeds after one another

I have a music blog that contains a series of youtube and soundcloud embeds.
I would like to automatically play all of the embedded content on the page one after another. In other words after a youtube embed that I've played ends, I would like the next embed to start playing whether it be from soundcloud or youtube and vice versa.
The rendered HTML looks like this:
<span class="soundcloud_embed" id="soundcloud_post_308">
<iframe id="ui-id-1" width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F103518792&show_artwork=true&secret_token=s-LnOTK"></iframe>
</span>
<span class="youtube_embed" id="youtube_post_309">
<iframe id="ui-id-2" width="528" height="190" src="//www.youtube.com/embed/Y3CYKXBEtf0" frameborder="0" allowfullscreen></iframe>
</span>
<span class="youtube_embed" id="youtube_post_310">
<iframe id="ui-id-3" width="528" height="190" src="//www.youtube.com/embed/yMx1FnkrhYc" frameborder="0" allowfullscreen></iframe>
</span>
Building off help I received from this source: Pause Youtube embed when playing Soundcloud embed
To keep track of which players are on the page, which api's they belong to, and which of them is currently playing:
var playerCurrentlyPlaying = {"api":null,"frameID":null};
var players = {"yt":{},"sc":{}};
I need to define a generic playNext function that is called in the event that playerCurrentlyPlaying comes to an end. Depending on the api of the next embed, the playNext function has to execute the proper play command. In order to find which embed is next, the function can perhaps increment the ID of the currentlyPlaying iframe by 1. Such that if id="ui-id-2" has just ended then id="ui-id-3" should play.
Sometimes these youtube videos crash and say things like "video no longer exists" or "uploader has made this unavailable in your country". In these cases, how can I check for a crash and skip to the next incremented ID (e.g. id="ui-id-4") ?
This video no longer exists:
<span class="youtube_embed" id="youtube_post_311">
<iframe id="ui-id-4" width="528" height="190" src="//www.youtube.com/embed/Ym3DgqNTzyc" frameborder="0" allowfullscreen></iframe>
</span>
You've got two questions in one, here. I'll try to address them both.
In terms of making the next player auto-play, there are two small steps you'll need to take. The first is to bind your player objects to their API's respective event signaling that the media is done playing. For YouTube, your event listener would look something like this:
onYTPlayerStateChange = function (event) {
if (event.data == YT.PlayerState.PLAYING) {
onYTPlay(event.target.a.id);
}
else if (event.data == YT.PlayerState.ENDED) {
playNextPlayer();
}
};
Where playNextPlayer() is this generic function you mention you need to define. For your Soundcloud embeds, your event bindings would look something like this, now:
(function () {
$(".soundcloud_embed iframe").each(function () {
var frameid = $(this).attr('id');
players["sc"][frameid] = {};
players["sc"][frameid] = {
"widget": SC.Widget(document.getElementById(frameid)),
"firstplay": true
};
players["sc"][frameid]["widget"].bind(SC.Widget.Events.READY, function () {
players["sc"][frameid]["widget"].bind(SC.Widget.Events.PLAY, function () {
onSCPlay(frameid, SC.Widget.Events.PLAY);
});
players["sc"][frameid]["widget"].bind(SC.Widget.Events.PLAY_PROGRESS, function () {
onSCPlay(frameid, SC.Widget.Events.PLAY_PROGRESS);
});
players["sc"][frameid]["widget"].bind(SC.Widget.Events.FINISH, function () {
playNextPlayer();
});
});
});
}());
Once you've got those bindings in place, the playNextPlayer function will need to determine what the next player is, what API it comes from, and then execute that API's play call. Something like this:
playNextPlayer = function() {
var nextIdNum=parseInt(playerCurrentlyPlaying["frameID"].split("-").pop())+1;
nextFrameId="ui-id-"+nextIdNum;
switch($("#"+nextFrameId).parent().attr('class')) {
case "youtube_embed":
api="yt";
players[api][nextFrameId].playVideo();
break;
case "soundcloud_embed":
api="sc";
players[api][nextFrameId]["widget"].play();
break;
}
playerCurrentlyPlaying["api"]=api;
playerCurrentlyPlaying["frameID"]=nextFrameId;
};
Keep in mind that there's no error handling built in to this sample code; you'll have to write some to handle cases where the IDs aren't sequential, for example, or what to do when its out of iframes to play.
As to your second question -- to determine whether or not a video is playable, you'll have to set up some error event listeners as well as the playback event listeners.
function onYouTubeIframeAPIReady() {
$(".youtube_embed iframe").each(function () {
players["yt"][$(this).attr('id')] = new YT.Player($(this).attr('id'), {
events: {
'onError': seeError,
'onStateChange': onYTPlayerStateChange
}
});
});
}
The seeError function can then be defined in such a way that it determines what player threw the error (using the event.target.a.id parameter in way similar to how it's being done with the state change event listeners), and then leverages the same generic playNextPlayer function. Keep in mind that if a Youtube video doesn't exist in that way, it will NOT generate a "PLAYING" event, so you'll have to set the proper playerCurrentlyPlaying values in your error listener as well, just to make sure the system then properly advances.
The YouTube player is supposed to throw different types of errors based on whether the video doesn't exist, whether it isn't playable in a particular country, etc. See here: https://developers.google.com/youtube/js_api_reference#Events under the "onError" section to see what these different codes are supposed to be. I say 'supposed to' because it looks like, right now, it's just throwing code 0 for all "can't play" errors.
Here's a working fiddle which does all of the above (you can switch the ids of the soundcloud and youtube iframes to verify that the advancement works both directions). This fiddle also instantiates an onError listener but doesn't define what it will do. Shouldn't be hard for you to get that to work, though.
http://jsfiddle.net/jlmcdonald/NqRqm/8/

Windows 8 (JavaScript): Multiple <video> tags with same webcam source: Possible?

I am developing a metro app using JavaScript and am trying to display two videos from the webcam simultaneously (one of them will, in the end, have a filter applied to it). However, I get an error whenever I try to set them both to use the webcam as a source,,,, Is there a good way to hand this situation?
Thanks!
Edit: Here is some code:
(Javascript)
var mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
//...set properties of captureInitSettings...
mediaCaptureMgr.initializeAsync(captureInitSettings).then(function (result) {
var video1 = id("Video1"); //function to get html element with id
video1.src = URL.createObjectURL(mediaCaptureMgr, false); //does not matter if false is switched to true
var video2 = id("Video2");
video2.src = video1.src;//could also use var x = URL.create... then set video1.src/video2.src = x; still won't work.
},
errorHandler);
(HTML)
<video id="Video1" autoplay></video>
<video id="Video2" autoplay></video>
I can fire the JS through a Click event or Load event--doesn't matter--only Video1 gets the webcam video. Video2 doesn't work. Thoughts?
Thanks!
Been playing a bit with getUserMedia in a similar fashion in Chrome lately, and I'm wondering if canvas in Metro is acceptable for your second video playback, seeing as you're planning on doing filtering anyway, seems like you may have to go this route regardless?
That said, I don't know anything about the Metro javascript environment, but looking at your example and knowing how I'd do it in a supported browser:
var video1 = id("Video1");
var canvas = id('canvas');
var context = canvas.getContext('2d');
context.drawImage(video1, 0, 0);
Of course, this would only work if you are drawing that image for each frame of video, which would be a breeze if there's some analog of window.requestAnimationFrame.

How to pause a YouTube player when hiding the iframe?

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>Click here 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 -->
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>Click here 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 />
close
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.
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":""}', '*')
});
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>
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).
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.
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.
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.

Categories