Pausing YouTube & Vimeo Videos via postMessage

Posted on 24th October 2015 in Code, Tips, Tutorials.

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

Whilst there are better ways of including YouTube or Vimeo videos into your site and regaining full control over your player, there really isn’t a more elegant solution for sites that run PHP content management systems such as WordPress, as you would need to use a lot of inline JavaScript to include these for YouTube, or add a specific ID to each Vimeo player. See here and here for more information about this. Overall, I find that this method is much easier as you can loop through your items, output the iframe and then control these using the above 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!

Tags

Sharing