How to get the duration of a video in iframe?

Member

by brandy , in category: Javascript , 2 months ago

How to get the duration of a video in iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 2 months ago

@brandy 

To get the duration of a video in an iframe, you can use the JavaScript postMessage API to communicate with the content within the iframe. Here is an example code snippet showing how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<iframe id="videoFrame" src="https://www.example.com/video" width="560" height="315"></iframe>

<script>
  const videoFrame = document.getElementById('videoFrame');
  videoFrame.addEventListener('load', function() {
    videoFrame.contentWindow.postMessage('getDuration', '*');
  });

  window.addEventListener('message', function(event) {
    if(event.data.type === 'duration') {
      const duration = event.data.duration;
      console.log('Video duration: ' + duration);
    }
  });
</script>


In the embedded video's webpage content, you need to listen for the 'message' event and respond with the video duration:

1
2
3
4
5
6
7
 window.addEventListener('message', function(event) {
    if(event.data === 'getDuration') {
      const video = document.querySelector('video');
      const duration = video.duration;
      window.parent.postMessage({ type: 'duration', duration: duration }, '*');
    }
  });


By sending a message requesting the duration of the video, the embedded content will respond with the duration value through the postMessage API.