【问题标题】:Replacing youtube iframe src breaks autoplay更换 youtube iframe src 会中断自动播放
【发布时间】:2018-07-19 10:04:54
【问题描述】:

我的 youtube 视频 iframe 在模态中需要在模态打开时自动播放,所以当模态打开时,我将 iframe 的 src 设置为带有 ?autoplay=1 的视频嵌入 URL。这适用于第一个视频,任何其他视频都不会自动播放。视频加载正常,我可以播放它们。他们只是不尊重autoplay 选项。

这是我用来替换 iframe 的 src 的代码:

$modalVideoPreviewIframe.attr('src', sessionPreviewVideoId && `https://www.youtube.com/embed/${sessionPreviewVideoId}?autoplay=1`);

我还尝试使用 jquery 的 clonereplaceWith 在设置其 src 之前将 iframe 替换为新元素:

const $modalVideoPreviewIframeClone = $modalVideoPreviewIframe.attr('src', 'about:blank').clone();
$modalVideoPreviewIframe.replaceWith($modalVideoPreviewIframeClone);
$modalVideoPreviewIframe = $modalVideoPreviewIframeClone;
$modalVideoPreviewIframe.attr('src', sessionPreviewVideoId && `https://www.youtube.com/embed/${sessionPreviewVideoId}?autoplay=1`);

【问题讨论】:

  • 为什么不使用youtube iframe api
  • @gaetanoM 我认为我不需要它。我现在添加它是因为我已经在这个愚蠢的视频问题上花费了太多时间。
  • 太棒了。 YouTube SDK 不工作。 new Player 从不发出 onReadyonError。我想我要写另一个问题了..
  • 控制台有错误吗?
  • 没有。我想到了。它默默地失败了,因为我通过了#my-id 而不是my-id。期望 id 字符串而不是查询字符串是一种粗俗的做法。无论如何,我要结束这个问题,因为我的问题已经解决了。

标签: javascript jquery iframe youtube


【解决方案1】:

我最终使用了YouTube iframe SDK

$('#session-modal-video').replaceWith('<div id="session-modal-video"></div>');
const player = new YT.Player('session-modal-video', {
  height: '390',
  width: '640',
  videoId: sessionPreviewVideoId,
  events: {
    'onReady'() {
      if(autoplay) {
        player.playVideo();
      }
    },
    'onError'(error) {
      console.log('Failed to create Youtube video player', error)
    }
  }
});

【讨论】:

    猜你喜欢
    • 2015-04-11
    • 2012-10-06
    • 1970-01-01
    • 2023-04-09
    • 2018-10-21
    • 2016-09-30
    • 2018-07-14
    • 2018-07-21
    • 2014-12-08
    相关资源
    最近更新 更多