小提琴链接:源代码 https://jsfiddle.net/hua2ge7b/1/ - Preview https://jsfiddle.net/hua2ge7b/1/show/ - 小版 http://jsfiddle.net/8R5y6/
更新:这个小函数只会在一个方向上执行代码。如果您想要完整的支持(例如事件侦听器/获取器),请查看at 在 jQuery 中监听 Youtube 事件 https://stackoverflow.com/a/7988536/938089?listening-for-youtube-event-in-javascript-or-jquery)
经过深入的代码分析,我创建了一个函数:function callPlayer
请求对任何带框架的 YouTube 视频进行函数调用。请参阅YouTube API 参考 https://developers.google.com/youtube/js_api_reference#Operations获取可能的函数调用的完整列表。阅读源代码中的注释以获得解释。
2012 年 5 月 17 日,代码大小增加了一倍,以照顾玩家的就绪状态。如果您需要一个不处理玩家就绪状态的紧凑函数,请参阅http://jsfiddle.net/8R5y6/ http://jsfiddle.net/8R5y6/.
/**
* @author Rob W <[email protected] /cdn-cgi/l/email-protection>
* @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);
}
}
Usage:
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:“不起作用”不是一个明确的描述。您收到任何错误消息吗?请出示相关代码。
Q: playVideo
不播放视频。
A:播放需要用户交互,并且需要存在allow="autoplay"
在 iframe 上。看https://developers.google.com/web/updates/2017/09/autoplay-policy-changes https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
Q:我已经使用嵌入了 YouTube 视频<iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />
但该函数不执行任何函数!
A: 还得加上?enablejsapi=1
在您的网址末尾:/embed/vid_id?enablejsapi=1
.
Q:我收到错误消息“指定了无效或非法的字符串”。为什么?
A:API 在本地主机上无法正常运行(file://
)。在线托管您的(测试)页面,或使用JSFiddle http://jsfiddle.net。示例:请参阅此答案顶部的链接。
Q: 你怎么知道这个的?
A:我花了一些时间手动解释 API 的源代码。我的结论是我必须使用postMessage https://developer.mozilla.org/en/DOM/window.postMessage方法。为了知道要传递哪些参数,我创建了一个拦截消息的 Chrome 扩展。可以下载扩展的源代码here https://robwu.nl/postMessage-debugging.zip.
Q: 支持哪些浏览器?
A: 每个支持的浏览器JSON http://caniuse.com/#feat=json and postMessage http://caniuse.com/#feat=x-doc-messaging.
- IE 8+
- Firefox 3.6+(实际上是 3.5,但是
document.readyState
在3.6中实现)
- 歌剧 10.50+
- 野生动物园 4+
- 铬3+
相关答案/实施:使用 jQuery 淡入带帧视频 https://stackoverflow.com/a/7866323/938089/jquery-fade-in-youtube-iframe-embed
完整的API支持:在 jQuery 中监听 Youtube 事件 https://stackoverflow.com/a/7988536/938089?listening-for-youtube-event-in-javascript-or-jquery)
官方API:https://developers.google.com/youtube/iframe_api_reference https://developers.google.com/youtube/iframe_api_reference
修订记录
- 2012 年 5 月 17 日
实施的onYouTubePlayerReady
: callPlayer('frame_id', function() { ... })
.
当玩家尚未准备好时,函数会自动排队。
- 2012年7月24日
已更新并在支持的浏览器中成功测试(展望未来)。
- 2013 年 10 月 10 日
当函数作为参数传递时,
callPlayer
强制检查准备情况。这是需要的,因为当callPlayer
在文档准备好时插入 iframe 后立即调用,它无法确定 iframe 是否已完全准备好。在 Internet Explorer 和 Firefox 中,这种情况会导致过早调用postMessage
,被忽略了。
- 2013 年 12 月 12 日,建议添加
&origin=*
在网址中。
- 2014 年 3 月 2 日,撤回删除建议
&origin=*
到网址。
- 2019 年 4 月 9 日,修复了在页面准备好之前加载 YouTube 时导致无限递归的错误。添加有关自动播放的注释。