没有允许展示的 YouTube iframe

mar*_*ico 5 javascript iframe youtube-iframe-api

我正在为内容管理系统管理 UI 构建扩展。该扩展由 CMS 在沙盒 iframe 中托管。

扩展的目的是嵌入 YouTube 视频,以便用户能够看到其预览。所以它是沙盒 iframe 中的一个 iframe。

我遇到的问题是沙箱(父 iframe)没有allow-presentation允许,这导致在 YouTube 嵌入代码中触发以下异常:

DOMException: Failed to construct 'PresentationRequest': The document is sandboxed and lacks the 'allow-presentation' 
Run Code Online (Sandbox Code Playgroud)

视频工作正常,但未处理的错误正在生成不需要的调试断点,并向浏览器控制台发送垃圾邮件。

我试图用?fs=0参数禁用全屏模式,但仍然调用代码并且仍然抛出错误。

有没有办法使嵌入代码在没有启用允许呈现的 iframe 中工作而不会出错?

小智 0

将其添加到创建 YouTube 播放器的 onYouTubeIframeAPIReady() 函数中,将其添加到player = new YT.Player (...) 部分下(检查代码片段) PS 它仍然会触发您的控制台错误,但只会触发一次,因为它默认情况下,将从 YouTube API 加载,无需该参数,如果您知道更好的方法,请告诉我。

  player.h.attributes.sandbox.value = "allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation";
Run Code Online (Sandbox Code Playgroud)

  player.h.attributes.sandbox.value = "allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation";
Run Code Online (Sandbox Code Playgroud)
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '360',
    width: '640',
    videoId: 'kbOBVUBX6E4',
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
  /*ADD THIS HERE SO IT UPDATED THE IFRAME PARAMETERS AFTER ITS GOTEN RENDERED*/
  player.h.attributes.sandbox.value = "allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation";
}

function onPlayerReady(event) {
  event.target.playVideo();


}


var done = false;

function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.PLAYING && !done) {
    setTimeout(stopVideo, 6000);
    done = true;
  }
}

function stopVideo() {
  player.stopVideo();
}
Run Code Online (Sandbox Code Playgroud)