Home > Software design >  Play video in Iframe from a external button
Play video in Iframe from a external button

Time:11-12

Is it possible to start video play back of YouTube iframe from an external button?

<button>Play Button</button>

<iframe width="560" height="315" src="https://www.youtube.com/embed/HJtJXMKpl2g" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Disclamer Note: The iframe video doesn't belongs to me.

CodePudding user response:

Yeah, it is possible. Try this and adjust it as you deserve:

<body>

<div class="bgimg w3-display-container w3-animate-opacity w3-text-white">
<div class="w3-display-middle">
<h1 class="w3-jumbo w3-animate-top">Click on "Play Button"</h1>
<hr class="w3-border-grey" style="margin:auto;width:40%">
  <p><button class="w3-center center transparent_btn" 
onclick="play1()">Play Button</button></p>
  <div id="youtube-frame"></div>
  </div>
</div>
</body>

<script>
function play1() { 
    var frame = document.getElementById("youtube-frame");
    frame.innerHTML = "<iframe width='560' height='315' src='https://www.youtube.com/embed/AkFs3YzxN_E' frameborder='0' allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>";
  }
</script>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Since this video is in iframe and in another host, by secure reasons you can't access to inner structure of that iframe by

const iframe = document.getElementById("myFrame");
const video = iframe.contentWindow.document.getElementsByTagName("video")[0];

video.play();

Adding "autoplay=1" to the src may help, but it can only start once video

iframe.setAttribute('src', iframe.getAttribute('src')   "?autoplay=1")
  • Related