首页 > 解决方案 > 通过外部按钮在 Iframe 中播放视频

问题描述

是否可以从外部按钮开始播放 YouTube iframe 的视频?

<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 视频不属于我。

标签: javascripthtmlcssiframeyoutube

解决方案


由于此视频位于 iframe 和另一个主机中,出于安全原因,您无法通过以下方式访问该 iframe 的内部结构

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

video.play();

添加"autoplay=1"到 src 可能会有所帮助,但它只能启动一次 video

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

推荐阅读