JavaScript
[JavaScript] 변수를 이용해 body 내부에 iframe 태그로 동영상 업로드
jane.dev
2021. 8. 26. 23:31
반응형
Youtube 영상 주소를 DB에 저장해 JSP 파일로 가져오고 싶은데,
1. 영상 공유버튼을 눌러 나오는 이 주소를 복사하기가 번거로움
2. 위 주소로 복사해서 가져올 때 마다 기본으로 설정된 width 와 height 속성을 변경하자니 번거로움
해당 주소를 그대로 복사해오면 브라우저에서 나타나는 크기
구현하고자 하는 로직
: 유튜브 URL을 DB에 저장하고, 생성한 DAO를 호출해 데이터를 불러오고 HTML 내부에서 출력될 영상 크기를 변경
https://www.youtube.com/watch?v=MtCMtC50gwY
유튜브 영상 URL
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/MtCMtC50gwY"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>
동영상 퍼가기에서 복사한 HTML iframe 태그
→ URL과 iframe 태그의 src 속성이 watch?v=
과 embed/
이 외에는 동일
<body>
<script type="text/javascript">
let address = "${address }";
body 태그 내부에 script를 작성해 변수를 생성(service에서 request.setAttribute를 통해 DB에 저장한 주소를 받아옴)
address = address.replace("watch?v=", "embed/");
<!-- 변수명.replace("찾은 문자열", "바꿀 문자열"); -->
JavaScript의 String 객체를 사용해 특정 문자열을 다른 문자열로 변경해서 변수에 저장
document.write("<iframe width='1120' height='630'
src='"
+ address
+ "'
title='YouTube video player'
frameborder='0'
allow='accelerometer;
autoplay;
clipboard-write;
encrypted-media;
gyroscope;
picture-in-picture'
allowfullscreen></iframe>");
</script>
</body>
width 와 height 속성에는 원하는 수치를 넣어주고, src 속성에 변경한 문자열로 구성된 주소를 address 라는 변수를 이용해 넣고 출력
→ document.write(); 괄호 내부의 String은 겹따옴표로 구성되어 있어서 iframe 태그안의 겹따옴표를 홑따옴표로 변경해줘야 함
브라우저에서 원하는 수치로 변경되어 출력된 영상 크기