Video event listener

Hello. I would like to listen for video events such as playing and paused.
I'm sure there's a function in H5P that already does this but I can't find it.
Please point me in the right direction.
Thanks!

icc's picture

Only H5P.Video has this, but usually, it's wrapped inside another content type. For Interactive Video you can do the following to monitor the video state: 

document.getElementsByClassName('h5p-iframe')[0].contentWindow.H5P.instances[0].video.on('stateChange', function (event) { console.log('New state:', event.data); });

The best way to find out where to look inside H5P.instances[n] is to inspect or debug the source code of the content type. Some content types may also make it impossible to reach the video instance and then the only solution is to add event listeners directly on the DOM element.

I get console output of:

New state: 1

New state: 3

New state: 2

 

New state: 1

Is there a way to translate this into things like play, pause or to get details like position/time i.e. what time the user paused the video?

Thanks for helping. This is really interesting :-)

icc's picture

Yes, try out this:

var iframeH5P = document.getElementsByClassName('h5p-iframe')[0].contentWindow.H5P
var iframeVideo = iframeH5P.instances[0].video;
iframeVideo.on('stateChange', function (event) { 
  switch (event.data) {
    case iframeH5P.Video.ENDED:
      console.log('Video ended after ' + iframeVideo.getCurrentTime() + ' seconds!');

      // Start over again?
      iframeVideo.play();

      if (iframeVideo.getDuration() > 15) {
        iframeVideo.seek(10);
      }

      break;

    case iframeH5P.Video.PLAYING:
      console.log('Playing'); 
      break;

    case iframeH5P.Video.PAUSED:
      console.log('Why you stop?');

      iframeVideo.setPlaybackRate(1.5); // Go fast
      break;

    case iframeH5P.Video.BUFFERING:
      console.log('Wait on your slow internet connection...');
      break;
  }
});

Hi,

I tried the code you provide in a JS snippet (using Wordpress woody snippets plugin) :

document.getElementsByClassName('h5p-iframe')[0].contentWindow.H5P.instances[0].video.on('stateChange', function (event) { console.log('New state:', event.data); });

 

But I don't know why the element H5P is inaccessible (undefined). If I use the DevTools of Google Chrome it's working.

I don't don't if you can help me? I don't understand why it's not working...

Thanks a lot!

Hi! Could you solve this issue since then? I'm having the same problem!

otacke's picture

Hi all!

I guess that in the console you didn't go into H5P's iframe context, or in a script you didn't wait for the content to be loaded.

Best,

Oliver 

Hi! Could you solve this issue since then? I'm having the same problem.