JavaScript で youtube 動画を複数おってきていっきにみる
大雑把な流れと使ったAPI
-
youtube実行するAPIキーを取得(手順は適当なページを参考)
-
youtube 表示する枠を作る(youtube player api の読込)
https://developers.google.com/youtube/iframe_api_reference?hl=ja -
youtube の api で動画をとってくる(youtube data api 実行)
https://developers.google.com/youtube/v3/docs/search/list
index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<input type="text" id="word"></text>
<button id="find">検索</button>
<div id="youtubeplayer"></div>
</body>
<script src="script.js"></script>
</html>
script.js
/** youtube data api key */
const youtubeDataApiKey = 'ここに取得したkeyを設定';
/** youtube player api の読込 */
const youtubePlayerApiScript = document.createElement('script');
youtubePlayerApiScript.src = "https://www.youtube.com/iframe_api";
const firstScript = document.querySelector('script');
firstScript.parentNode.insertBefore(youtubePlayerApiScript, firstScript);
/**
* youtube player の表示用 dom 追加、設定
*/
const players = new Array(20); // 表示したい数
function onYouTubePlayerAPIReady() {
for (let index = 0; index < players.length; index++) {
let pl = document.createElement('div');
pl.id = 'player' + index;
document.querySelector('#youtubeplayer').appendChild(pl);
players[index] = new YT.Player(pl.id, { width: 'auto', height: 'auto' });
}
}
/**
* 検索 ボタン押下で youtube api 実行して動画取得して設定
*/
document.querySelector('#find').addEventListener('click', async (e) => {
console.log(players);
const params = {
key: youtubeDataApiKey,
type: 'video',
part: 'id',
maxResults: players.length,
q: document.querySelector('#word'),
order: 'date',
};
const url = new URL('https://www.googleapis.com/youtube/v3/search');
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
const response = await fetch(url);
const json = await response.json();
console.log(json);
for (let index = 0; index < players.length && index < json.items.length; index++) {
players[index].loadVideoById({ videoId: json.items[index].id.videoId });
}
});