IT/HTML CSS JavaScript
유튜브 영상 삽입 (iframe, youtube data api v3)
HJ::
2023. 6. 8. 23:15
// apikey는 youtube data API v3을 사용해주었다.
const apiKey = '';
// json 형식의 movie.title을 detail.html에서 setItem 해준 상태
let movieName= localStorage.getItem("movie_name");
영화 이름을 가져와준다.
평점이 높은 역대 영화 리스트를 받아온 거라 데이터가 갱신이 되어도
movieName에는 그거에 맞춰서 변경된다.
const searchQuery = movieName+' trailer';
그것과 '(영화 제목) trailer' 로 키워드를 생성한다.
let url ='...search?part=snippet&q=' + encodeURIComponent(searchQuery) + '&key=' + apiKey;
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
let videoId = data.items[0].id.videoId;
playYouTubeVideo(videoId);
})
.catch(function(error) {
console.log('오류 발생:', error);
});
}
유튜브에 해당 키워드를 치고 맨 위에 있는 영상 링크를 가져와주는 작업이다.
function playYouTubeVideo(videoId) {
// iframe 요소 생성
var iframe = document.createElement('iframe');
iframe.src = 'https://www.youtube.com/embed/' + videoId + '?autoplay=1'; // autoplay 추가
iframe.width = '540';
iframe.height = '250';
iframe.allowFullscreen = true;
이런식으로 만들어준 url를 iframe 태그를 사용해주어서 완성시켜준다.