【问题标题】:Adding HTML attributes to iframe from YouTube Player API从 YouTube Player API 向 iframe 添加 HTML 属性
【发布时间】:2020-10-27 09:35:21
【问题描述】:

我正在使用 YouTube Player API 在网站上嵌入视频:

    let player = new YT.Player(videoElementID, {
      height: '390',
      width: '640',
      videoId: videoElementID,
      host: 'https://www.youtube-nocookie.com',
      playerVars: {
        origin: window.location.host,
        showinfo: 0,
        rel: 0,
        hl: 'da-dk'
      }

但现在需要向视频 iFrame 添加不受支持的属性,特别是属性 data-category-consentdata-consent-src。我还需要将 src 设置为空:

<iframe width="560" height="315" src="" data-category-consent="cookie_cat_statistic" data-consent-src="https://www.youtube.com/embed/3EeY_7ujsew" frameborder="0" allow="autoplay;"></iframe>

在读取页面 DOM 并继续使用 YouTube 播放器 API之前,有什么方法可以对 iFrame 执行这些更改?在获得同意之前,我需要避免使用 YouTube-cookie,这意味着在添加属性之前无法读取 iFrame。

【问题讨论】:

    标签: javascript html youtube-api


    【解决方案1】:

    我们也有类似的需求。因此通过 JQuery 添加了 data-category-consent 和 data-consent-src。下面是实现:

    <div id="playerId"></div>
    
    <script>
    new YT.Player(playerId, {
          height: '390',
          width: '640',
          videoId: videoElementID,
          host: 'https://www.youtube-nocookie.com',
          playerVars: {
            origin: window.location.host,
            showinfo: 0,
            rel: 0,
            hl: 'da-dk'
          }
    
     
    $('iframe#playerId').attr(
    {
           "data-category-consent": "cookie_cat_marketing",
           'data-consent-src': $('iframe#playerId').attr("src");
           "src":""
     });
    
    </script>
    

    【讨论】:

      【解决方案2】:

      基本上不使用库,创建 iframe 并自己填充。

      这个例子在这里不起作用,原因是:

      跨域请求被阻止:同源策略不允许读取 远程资源

      onclick = () => {
        yt.innerHTML = `<iframe width="560" height="315" src="https://www.youtube.com/embed/3EeY_7ujsew" data-category-consent="cookie_cat_statistic" data-consent-src="https://www.youtube.com/embed/3EeY_7ujsew" frameborder="0" allow="autoplay;"></iframe>`
      }
      Click to load the player<br>
      <div id="yt"></div>

      【讨论】:

        猜你喜欢
        • 2013-10-24
        • 2015-11-27
        • 2023-04-08
        • 1970-01-01
        • 2019-03-28
        • 2017-11-15
        • 2012-09-14
        • 1970-01-01
        • 2022-11-10
        相关资源
        最近更新 更多