YouTube iframe API: 如何控制已经在 HTML 中的 iframe 播放器?

我希望能够控制基于 iframe 的 YouTube 播放器。这个播放器已经在 HTML 中了,但是我想通过 JavaScriptAPI 来控制它们。

我一直在阅读 Iframe API 的文档,它解释了如何使用 API 向页面添加新的视频,然后使用 YouTube 播放器功能控制它:

var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('container', {
height: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}

该代码创建一个新的播放器对象,并将其分配给“播放器”,然后将其插入到 # Container div 中。然后我就可以操作“播放器”,并呼叫它的 playVideo()pauseVideo()等。

但我希望能够操作的 iframe 播放器已经在页面上。

我可以很容易地用旧的 embed 方法做到这一点,比如:

player = getElementById('whateverID');
player.playVideo();

但是这个在新的 iframe 中不起作用。如何分配页面上已有的 iframe 对象,然后在其上使用 API 函数?

226556 次浏览

小提琴链接: 源代码-预览-小版本的
更新: 这个小函数只在单个方向上执行代码。如果你想要完全的支持(例如事件监听器/getters) ,可以看看 < a href = “ https://stackoverflow.com/a/7988536/938089? listen-for-Youtube-Event-in-javascript-or-jQuery)”> Listingfor Youtube Event in jQuery

作为一个深入的代码分析的结果,我创建了一个函数: function callPlayer请求对任何框架 YouTube 视频的函数调用。查看 参考 YouTube Api以获得可能的函数调用的完整列表。请阅读源代码中的注释以获得解释。

在2012年5月17日,为了保证玩家的准备状态,代码大小增加了一倍。如果您需要一个紧凑的功能,不处理球员的就绪状态,请参阅 http://jsfiddle.net/8R5y6/

/**
* @author       Rob W <gwnRob@gmail.com>
* @website      https://stackoverflow.com/a/7513356/938089
* @version      20190409
* @description  Executes function on a framed YouTube video (see website link)
*               For a full list of possible functions, see:
*               https://developers.google.com/youtube/js_api_reference
* @param String frame_id The id of (the div containing) the frame
* @param String func     Desired function to call, eg. "playVideo"
*        (Function)      Function to call when the player is ready.
* @param Array  args     (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
var iframe = document.getElementById(frame_id);
if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
}


// When the player is not ready yet, add the event to a queue
// Each frame_id is associated with an own queue.
// Each queue has three possible states:
//  undefined = uninitialised / array = queue / .ready=true = ready
if (!callPlayer.queue) callPlayer.queue = {};
var queue = callPlayer.queue[frame_id],
domReady = document.readyState == 'complete';


if (domReady && !iframe) {
// DOM is ready and iframe does not exist. Log a message
window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
if (queue) clearInterval(queue.poller);
} else if (func === 'listening') {
// Sending the "listener" message to the frame, to request status updates
if (iframe && iframe.contentWindow) {
func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
iframe.contentWindow.postMessage(func, '*');
}
} else if ((!queue || !queue.ready) && (
!domReady ||
iframe && !iframe.contentWindow ||
typeof func === 'function')) {
if (!queue) queue = callPlayer.queue[frame_id] = [];
queue.push([func, args]);
if (!('poller' in queue)) {
// keep polling until the document and frame is ready
queue.poller = setInterval(function() {
callPlayer(frame_id, 'listening');
}, 250);
// Add a global "message" event listener, to catch status updates:
messageEvent(1, function runOnceReady(e) {
if (!iframe) {
iframe = document.getElementById(frame_id);
if (!iframe) return;
if (iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
if (!iframe) return;
}
}
if (e.source === iframe.contentWindow) {
// Assume that the player is ready if we receive a
// message from the iframe
clearInterval(queue.poller);
queue.ready = true;
messageEvent(0, runOnceReady);
// .. and release the queue:
while (tmp = queue.shift()) {
callPlayer(frame_id, tmp[0], tmp[1]);
}
}
}, false);
}
} else if (iframe && iframe.contentWindow) {
// When a function is supplied, just call it (like "onYouTubePlayerReady")
if (func.call) return func();
// Frame exists, send message
iframe.contentWindow.postMessage(JSON.stringify({
"event": "command",
"func": func,
"args": args || [],
"id": frame_id
}), "*");
}
/* IE8 does not support addEventListener... */
function messageEvent(add, listener) {
var w3 = add ? window.addEventListener : window.removeEventListener;
w3 ?
w3('message', listener, !1)
:
(add ? window.attachEvent : window.detachEvent)('onmessage', listener);
}
}

用法:

callPlayer("whateverID", function() {
// This function runs once the player is ready ("onYouTubePlayerReady")
callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");

可能的问题(及答案) :

Q : 这不管用!
A : “无法工作”不是一个明确的描述。是否收到任何错误消息? 请显示相关代码。

问: playVideo不播放视频。
回放需要用户交互,并且在 iframe 上存在 allow="autoplay",请参阅 https://developers.google.com/web/updates/2017/09/autoplay-policy-changes和 https://developer.mozilla.org/en-us/docs/web/media/autoplay_guide

Q : 我使用 <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />嵌入了一个 YouTube 视频,但是这个函数不执行任何函数!
A : 必须在 URL 的末尾添加 ?enablejsapi=1: /embed/vid_id?enablejsapi=1

Q : 我收到错误消息“指定了无效或非法字符串”。为什么?
A : API 在本地主机(file://)上无法正常工作。在线托管您的(测试)页面,或者使用 JSFiddle。示例: 请参阅答案顶部的链接。

问: 你怎么知道的?
A : 我花了一些时间手动解释 API 的源代码。我的结论是我必须使用 postMessage方法。为了知道应该传递哪些参数,我创建了一个 Chrome 扩展来拦截消息。扩展的源代码可以下载 给你

Q : 支持哪些浏览器?
A : 每个支持 JSONpostMessage的浏览器。

  • IE8 +
  • Firefox 3.6 + (实际上是3.5,但是 document.readyState是在3.6中实现的)
  • Opera 10.50 +
  • Safari 4 +
  • Chrome 3 +

相关答案/实现: 使用 jQuery 淡入框架视频
完整的 API 支持: 在 jQuery 中监听 Youtube 事件
官方 API: https://developers.google.com/youtube/iframe_api_reference

修订历史

  • 在2012年5月17日获发
    实现了 onYouTubePlayerReady: callPlayer('frame_id', function() { ... })
    当播放器还没有准备好时,函数会自动排队。
  • 2012年7月24日
    在支持的浏览器中更新并成功测试(展望未来)。
  • 2013年10月10日 当函数作为参数传递时,callPlayer强制执行准备就绪检查。这是必需的,因为当文档准备好插入 iframe 之后立即调用 callPlayer时,它不能确定 iframe 是否完全准备好了。在 Internet Explorer 和 Firefox 中,这种情况导致过早地调用 postMessage,这被忽略了。
  • 2013年12月12日,建议在 URL 中添加 &origin=*
  • 2014年3月2日,撤回删除 &origin=*到 URL 的建议。
  • 2019年4月9日,修复了当 YouTube 在页面准备好之前加载时导致无限递归的 bug。添加关于自动播放的注释。

看起来 YouTube 已经更新了他们的 JS API,所以这是默认可用的!您可以使用现有的 YouTube iframe 的 ID..。

<iframe id="player" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>

... 在你的 JS 里..。

var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
}


function onPlayerStateChange() {
//...
}

... 构造函数将使用您现有的 iframe 而不是替换为一个新的。这也意味着您不必向构造函数指定 video Id。

参见 正在加载视频播放器

您可以使用少得多的代码来实现这一点:

function callPlayer(func, args) {
var i = 0,
iframes = document.getElementsByTagName('iframe'),
src = '';
for (i = 0; i < iframes.length; i += 1) {
src = iframes[i].getAttribute('src');
if (src && src.indexOf('youtube.com/embed') !== -1) {
iframes[i].contentWindow.postMessage(JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
}), '*');
}
}
}

实例: Http://jsfiddle.net/kmturley/g6p5h/296/

上面是我自己的 Kim T 代码版本,它与一些 jQuery 结合在一起,并允许定位特定的 iframe。

$(function() {
callPlayer($('#iframe')[0], 'unMute');
});


function callPlayer(iframe, func, args) {
if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
} ), '*');
}
}

谢谢你的回答。

我一直在 Cordova 应用程序中使用它,以避免必须加载 API,这样我就可以轻松地控制动态加载的 iframe。

我一直希望能够从 iframe 中提取信息,比如状态(getPlayerState)和时间(getCurrentTime)。

Rob W 帮助强调了使用 postMessage 的 API 是如何工作的,但是当然这只是向一个方向发送信息,从我们的 Web 页面发送到 iframe。访问 getter 需要我们监听从 iframe 发回给我们的消息。

我花了一些时间想出如何调整 Rob W 的答案来激活和听取 iframe 返回的消息。我基本上搜索了 YouTube iframe 中的源代码,直到找到负责发送和接收消息的代码。

关键是将“事件”改为“监听”,这基本上给了访问所有设计用于返回值的方法的权限。

下面是我的解决方案,请注意,我已经切换到“监听”只有当获取器被请求,你可以调整条件,以包括额外的方法。

进一步注意,您可以通过向 window.onmessage 添加 console.log (e)查看从 iframe 发送的所有消息。你会注意到,一旦监听被激活,你会收到不断更新,其中包括当前的视频时间。调用 getPlayerState 之类的 getter 将激活这些持续更新,但只会在视频状态发生更改时发送涉及视频状态的消息。

function callPlayer(iframe, func, args) {
iframe=document.getElementById(iframe);
var event = "command";
if(func.indexOf('get')>-1){
event = "listening";
}


if ( iframe&&iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': event,
'func': func,
'args': args || []
}), '*');
}
}
window.onmessage = function(e){
var data = JSON.parse(e.data);
data = data.info;
if(data.currentTime){
console.log("The current time is "+data.currentTime);
}
if(data.playerState){
console.log("The player state is "+data.playerState);
}
}

我在上面的例子中遇到了一些问题,所以我只是在源代码中用 JS 点击插入了 iframe,它对我来说很好用。我也有可能使用 Vimeo 或 YouTube,所以我需要能够处理这些问题。

这个解决方案并不神奇,可以清除,但这对我很有效。我也不喜欢 jQuery,但是这个项目已经在使用它了,我只是在重构现有的代码,你可以随意清理或者转换成普通的 JS:)

<!-- HTML -->
<div class="iframe" data-player="viemo" data-src="$PageComponentVideo.VideoId"></div>




<!-- jQuery -->
$(".btnVideoPlay").on("click", function (e) {
var iframe = $(this).parents(".video-play").siblings(".iframe");
iframe.show();


if (iframe.data("player") === "youtube") {
autoPlayVideo(iframe, iframe.data("src"), "100%", "100%");
} else {
autoPlayVideo(iframe, iframe.data("src"), "100%", "100%", true);
}
});


function autoPlayVideo(iframe, vcode, width, height, isVimeo) {
if (isVimeo) {
iframe.html(
'<iframe width="' +
width +
'" height="' +
height +
'" src="https://player.vimeo.com/video/' +
vcode +
'?color=ff9933&portrait=0&autoplay=1" frameborder="0" allowfullscreen wmode="Opaque"></iframe>'
);
} else {
iframe.html(
'<iframe width="' +
width +
'" height="' +
height +
'" src="https://www.youtube.com/embed/' +
vcode +
'?autoplay=1&loop=1&rel=0&wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>'
);
}
}

一个快速的解决方案是 如果请求不成问题,您希望在诸如 show/hide 视频之类的事情上采用这种行为,那就是删除/添加 iframe,或者清理并填充 src

const stopPlayerHack = (iframe) => {
let src = iframe.getAttribute('src');
iframe.setAttribute('src', '');
iframe.setAttribute('src', src);
}

Iframe 将被删除,停止播放,并将在此之后立即加载。在我的例子中,我已经改进了代码,只在 lightbox 打开时再次设置 src,因此只有在用户要求查看视频时才会加载。