Main menu

How to: Integrate Youtube IFrame API and Youtube field in Drupal 7

Published by dnovikov on Wed, 09/03/2014 - 12:20

If you are using Youtube module to display videos at your site, you may want to add some reactions on the Youtube player events. For instance, I did so for Google Analytics tracking capabilities.

To enable usage of the Youtube IFrame API, you need to add some Javascript code. Please remember: do not put it in Drupal behaviors wrapper!

The code is like this:

// Load YouTube IFrame API.
var tag = document.createElement('script');

tag.src = "";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Add an event listener to the existing iframe#youtube_video
function onYouTubeIframeAPIReady() {
  new YT.Player('youtube_video', {
    events: {
      'onStateChange': onPlayerStateChange

// Process player events.
function onPlayerStateChange(event) {
  switch ( {
    case YT.PlayerState.PLAYING:
      // Do something here.
    case YT.PlayerState.ENDED:
      // Do something here.


Where do I put this code? In which file?

For the future reference, you should put this code in a sites/all/themes/YOUR_THEME/js/script.js and add a reference for that file in YOUR_THEME/, then clear drupal caches

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.