我想能够控制基于iframe的YouTube播放器。这些播放器将已经在超文本标记语言中,但我想通过JavaScript应用程序接口控制它们。
我一直在读documentation for the iframe API,它解释了如何使用API向页面添加新视频,然后使用YouTube播放器函数控制它:
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('container', {
height: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
该代码创建一个新的player对象并将其分配给'player',然后将其插入到#container div中。然后我可以对'player‘进行操作,并对其调用playVideo()
、pauseVideo()
等。
但是我想能够操作已经在页面上的iframe播放器。
我可以用旧的embed方法很容易做到这一点,如下所示:
player = getElementById('whateverID');
player.playVideo();
但这不适用于新的iframe。如何分配页面上已有的iframe对象,然后在其上使用API函数?
发布于 2011-09-22 18:30:53
小提琴链接: - -
更新:这个小函数只能在一个方向上执行代码。如果你想要完整的支持(例如事件侦听器/ getters),可以在 上查看
作为深入代码分析的结果,我创建了一个函数:function callPlayer
请求对任何带帧的YouTube视频进行函数调用。请参阅YouTube Api reference以获取可能的函数调用的完整列表。请阅读源代码中的注释以获得解释。
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:“不工作”不是一个清晰的描述。您是否收到任何错误消息?请出示相关代码。
Q:playVideo
不播放视频。
A:播放需要用户交互,并在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:我收到错误消息“指定了无效或非法的字符串”。为什么?
API A:在本地主机(file://
)上无法正常工作。在线托管您的(测试)页面,或使用JSFiddle。示例:请参阅此答案顶部的链接。
Q:你是怎么知道的?
API:我花了一些时间来手动解释的源代码。我得出结论,我必须使用postMessage
方法。为了知道要传递哪些参数,我创建了一个拦截消息的Chrome扩展。该扩展的源代码可以从here下载。
Q:支持哪些浏览器?
A:所有支持JSON和postMessage
的浏览器。
document.readyState
是在3.6版本中实现的)相关答案/实施:Fade-in a framed video using jQuery
完整接口支持:Listening for Youtube Event in jQuery
官方接口:https://developers.google.com/youtube/iframe_api_reference
修订历史
实现的onYouTubePlayerReady
:callPlayer('frame_id', function() { ... })
。
当播放器还没有准备好时,函数会自动排队。
已更新并已在支持的浏览器中成功测试(展望未来)。
callPlayer
会强制执行就绪检查。这是必需的,因为当文档准备就绪时,在插入iframe之后立即调用callPlayer
时,它不能确定iframe是否完全就绪。在In和火狐中,这种情况导致过早调用postMessage
,因此被忽略。
&origin=*
。
&origin=*
的建议。
发布于 2013-07-30 05:39:00
看起来YouTube已经更新了他们的JS,所以这是默认可用的!您可以使用现有的YouTube iframe的ID...
<iframe id="player" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>
...in你的JS...
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange() {
//...
}
...and构造函数将使用您现有的iframe,而不是用新的iframe替换它。这也意味着您不必指定构造函数的videoId。
发布于 2014-12-11 04:42:34
你可以用更少的代码来做到这一点:
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 || []
}), '*');
}
}
}
https://stackoverflow.com/questions/7443578
复制相似问题