YouTube iframe 不响应 postMessage 命令

Nin*_*and 3 javascript youtube iframe postmessage

我正在尝试使用来自父级的 postMessage 命令来控制 YouTube iframe,但它似乎不起作用。

\n\n

由于多种原因,我没有使用 YouTube API,只是使用带有 YouTube 嵌入视频的普通 iframe。

\n\n
<iframe id="video-player" :src="\'https://www.youtube.com/embed/\' + code + \'?autoplay=1\'"\n  seamless sandbox="allow-scripts allow-same-origin allow-presentation"></iframe>\n
Run Code Online (Sandbox Code Playgroud)\n\n

我尝试发送命令的方式是:

\n\n
var iframe = document.getElementById(\'video-player\');\niframe.contentWindow.postMessage(JSON.stringify(\n  { event: \'command\', func: \'pauseVideo\' }), \'https://www.youtube.com\');\n
Run Code Online (Sandbox Code Playgroud)\n\n

看来 iframe 已被正确选择,但我不确定是否正在发送 postMessage 命令,因为视频会忽略它们。

\n\n

\xc2\xbf我做错了什么?

\n

Nin*_*and 6

我找到了解决方案。YouTube 网址需要查询参数“enablejsapi=1”。

<iframe id="video-player" :src="'https://www.youtube.com/embed/' + code + '?autoplay=1&enablejsapi=1'"
  seamless sandbox="allow-scripts allow-same-origin allow-presentation"></iframe>
Run Code Online (Sandbox Code Playgroud)

像这样它正确地监听 postMessage() 命令。