age*_*eto 144 javascript youtube-api youtube-javascript-api
我希望能够控制基于iframe的YouTube播放器.这些播放器已经在HTML中,但我想通过JavaScript API控制它们.
我一直在阅读iframe API的文档,该文档解释了如何使用API向页面添加新视频,然后使用YouTube播放器功能控制它:
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('container', {
height: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Run Code Online (Sandbox Code Playgroud)
该代码创建一个新的播放器对象并将其分配给"播放器",然后将其插入#container div中.然后,我可以在"播放器"和呼叫操作playVideo()
,pauseVideo()
就可以了,等等.
但我希望能够对已经在页面上的iframe播放器进行操作.
我可以使用旧的嵌入方法很容易地做到这一点,例如:
player = getElementById('whateverID');
player.playVideo();
Run Code Online (Sandbox Code Playgroud)
但这不适用于新的iframe.如何在页面上分配iframe对象,然后在其上使用API函数?
Rob*_*b W 305
小提琴链接:源代码 - 预览 - 小版本
更新:这个小功能只能在单个方向上执行代码.如果你想完全支持(如事件监听器/吸气),看看在jQuery的侦听YouTube事件
深度代码分析后,我创建了一个函数: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);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
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");
Run Code Online (Sandbox Code Playgroud)
问:它不起作用!
答:"不起作用"不是一个明确的描述.你收到任何错误信息吗?请出示相关代码.
问:我使用了嵌入的YouTube视频,playVideo
但该功能不执行任何功能!
答:您必须allow="autoplay"
在网址末尾添加:<iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />
.
问:我收到错误消息"指定了无效或非法字符串".为什么?
答:API在本地主机(?enablejsapi=1
)上无法正常运行.在线托管您的(测试)页面,或使用JSFiddle.示例:请参阅此答案顶部的链接.
问:你是怎么知道的?
答:我花了一些时间来手动解释API的来源.我总结说我必须使用这种/embed/vid_id?enablejsapi=1
方法.要知道要传递哪些参数,我创建了一个拦截邮件的Chrome扩展程序.可以在此处下载扩展的源代码.
问:支持哪些浏览器?
答:每个支持JSON和的浏览器file://
.
postMessage
在3.6中实现)相关答案/实现:使用jQuery
Full API支持淡入框架视频:在jQuery
官方API中收听Youtube事件:https://developers.google.com/youtube/iframe_api_reference
postMessage
:document.readyState
.onYouTubePlayerReady
强制检查准备情况.这是必需的,因为在callPlayer('frame_id', function() { ... })
文档准备好后插入iframe后立即调用时,它无法确定iframe是否已完全就绪.在Internet Explorer和Firefox中,此方案导致过早调用callPlayer
,但被忽略.callPlayer
URL.postMessage
网址的建议.Cle*_*usW 31
看起来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>
Run Code Online (Sandbox Code Playgroud)
......在你的JS ......
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange() {
//...
}
Run Code Online (Sandbox Code Playgroud)
...而构造函数将使用您现有的iframe,而不是用新的iframe替换它.这也意味着您不必将videoId指定给构造函数.
请参阅加载视频播放器
Kim*_*m T 17
您可以使用更少的代码执行此操作:
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 || []
}), '*');
}
}
}
Run Code Online (Sandbox Code Playgroud)
工作示例: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 || []
} ), '*');
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
169767 次 |
最近记录: |