0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

youtube動画を検索して複数いっきにみる JavaScript

Last updated at Posted at 2023-01-26

JavaScript で youtube 動画を複数おってきていっきにみる
大雑把な流れと使ったAPI

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 });
    }
});
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?