Pausing YouTube & Vimeo Videos via postMessage
Posted on 24th October 2015 in Code, Tips, Tutorials.
postMessage we can communicate with an
<iframe> by posting data to it. The data that we would typically post to an
<iframe> would be something such as a command (although it really can be anything!).
To give a real world example of this, let’s say you have a carousel or a slider, and in the slides you have a mixture of images and videos coming from YouTube and/or Vimeo, in the form of
<iframe> elements. Since we can’t directly access the players inside these
<iframe> elements, the only way to control these is via user input, right?
Nope, we can actually post data to the
<iframe> provided that they have the required API parameters passed into their
src attribute. The API parameter for YouTube videos is “enablejsapi=1“, whilst the API parameter for Vimeo videos is “api=1“.
Take the following HTML for example:
We have a slider with two slides, one with a YouTube video and the other with a Vimeo video. We can post data to the videos by storing the
<iframe> as a variable, accessing it’s
contentWindow property, and finally posting our command to it via
postMessage. The data you can post is specific to the platform, for more information regarding YouTube, read more here. For Vimeo, read more here. In the below example, we are accessing the YouTube player, and posting a command telling the video to pause.
Back to our real world example, what happens if your user navigates to a slide containing a Vimeo or YouTube video, starts to play the video but loses interest, and wants to view the next slide? The video will continue to play in the background, which can only be bad for the user’s experience. Using
postMessage, we can simply tell the video to stop playing when the user changes the slide. I’ve created a pen detailing this, in the example I am using the popular Slick Carousel jQuery plugin, and binding a function to the plugins “beforeChange” event. Check the pen out, play a video and then change the slide.
postMessage as above.
Thanks for reading this post, to find out more about
postMessage, read more here. Please let me know your thoughts about this in the comments section below!