フィドルリンク:ソースコード-プレビュー-小さなバージョン
更新:この小さな関数は、一方向にのみコードを実行します。完全なサポート(イベントリスナー/ゲッターなど)が必要な場合は、jQueryでのYoutubeイベントのリッスンをご覧ください。
深いコード分析の結果として、私は関数を作成しました:function callPlayer
フレーム化されたYouTubeビデオで関数呼び出しを要求します。可能な関数呼び出しの完全なリストを取得するには、YouTubeApiリファレンスを参照してください。説明については、ソースコードのコメントを読んでください。
2012年5月17日、プレーヤーの準備完了状態を処理するために、コードサイズが2倍になりました。プレーヤーの準備完了状態を処理しないコンパクトな関数が必要な場合は、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:再生には、ユーザーの操作とallow="autoplay"
iframe上での存在が必要です。https://developers.google.com/web/updates/2017/09/autoplay-policy-changesおよびhttps://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guideを参照してください
Q:を使用してYouTubeビデオを埋め込みました<iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />
が、関数が関数を実行しません!
A?enablejsapi=1
: URLの最後に追加する必要があります: /embed/vid_id?enablejsapi=1
。
Q:「無効または不正な文字列が指定されました」というエラーメッセージが表示されます。なんで?
A:APIがローカルホストで正しく機能しません(file://
)。(テスト)ページをオンラインでホストするか、JSFiddleを使用します。例:この回答の上部にあるリンクを参照してください。
Q:どうやってこれを知ったのですか?
A:APIのソースを手動で解釈するためにしばらく時間を費やしました。私はそのpostMessage
方法を使わなければならないと結論付けました。渡す引数を知るために、メッセージをインターセプトするChrome拡張機能を作成しました。拡張機能のソースコードは、ここからダウンロードできます。
Q:どのブラウザがサポートされていますか?
A : JSONとをサポートするすべてのブラウザpostMessage
。
- IE 8+
- Firefox 3.6以降(実際には3.5ですが
document.readyState
、3.6で実装されました)
- Opera 10.50+
- Safari 4+
- Chrome3+
関連する回答/実装:jQueryを使用したフレーム化されたビデオのフェードイン
完全なAPIサポート: jQuery
公式APIでのYoutubeイベントのリッスン: 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=*
、URLを追加することをお勧めします。
- 2014年3月2日
&origin=*
、URLへの削除に関する推奨事項を撤回しました。
- 2019年4月9日、ページの準備が整う前にYouTubeが読み込まれると無限再帰が発生するバグを修正しました。自動再生に関するメモを追加します。