javascriptiframeyoutubepostmessage

Youtube iframe not responding to postMessage commands


I'm trying to control a YouTube iframe using postMessage commands from the parent, but it doesn't seem to work.

For a number of reasons I'm not using the YouTube API, just a normal iframe with a youtube embedded video.

<iframe id="video-player" :src="'https://www.youtube.com/embed/' + code + '?autoplay=1'"
  seamless sandbox="allow-scripts allow-same-origin allow-presentation"></iframe>

The way I'm trying to send commands is:

var iframe = document.getElementById('video-player');
iframe.contentWindow.postMessage(JSON.stringify(
  { event: 'command', func: 'pauseVideo' }), 'https://www.youtube.com');

It seems that the iframe is being selected correctly, but I'm not sure if the postMessage commands are being sent, as the video ignores them.

¿What am I doing wrong?


Solution

  • I found the solution. The YouTube url needs the query parameter "enablejsapi=1".

    <iframe id="video-player" :src="'https://www.youtube.com/embed/' + code + '?autoplay=1&enablejsapi=1'"
      seamless sandbox="allow-scripts allow-same-origin allow-presentation"></iframe>
    

    Like this it correctly listens to postMessage() commands.