프론트엔드/Tips

[자바스크립트] 댓글에 이미지, 비디오, 유튜브 등 첨부하기

Marshall K 2019. 4. 14. 22:50

내용 자체는 앞서 한 포스트에서 크게 바뀌지 않았습니다만, 조금 더 알아보고 수정하기 쉽게 재작업했습니다.


텍스트 내에서 url을 찾고, 그 url이 이미지인지, 비디오인지, 오디오인지, 유튜브 비디오인지 판별해서 적절한 태그로 감싸줍니다.

간단하게 댓글에 이미지 비디오 등을 넣고 싶으실 때 사용하시면 됩니다.


function autowrap() {
const c = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi, // 링크 찾기
i = /\.(?:jpe?g(:large)?|gif|png(:large)?|svg)$/i, // 이미지
x = /(?:\?original)$/i, // 티스토리 ?original 이미지
j = /\.(?:mp4|webm)$/i, // 비디오
k = /\.(?:mp3|ogg|wav)$/i, // 오디오
z = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?/g; // 유튜브 비디오

function mod(string) { // 스트링을 해당 태그로 변환
return string.replace(c, function (url) {
if (i.test(url)) {
return `<img src="${url}" class="autoImage" onclick="open_img('${url}')" />`
}
if (x.test(url)) {
return `<img src="${url}" class="autoImage" onclick="open_img('${url}')" />`
}
if (j.test(url)) {
return `<video autoplay muted loop playsinline src="${url}"></video>`
}
if (k.test(url)) {
return `<audio controls src="${url}"></audio>`
}
if (z.test(url)) {
return `<div class="youtubevid-wrapper"><div class="resvid"><iframe src="https://www.youtube.com/embed/${url.replace(z, "")}?rel=0&playsinline=1" frameborder="0" allowfullscreen></iframe></div></div>`
} else {
return `<a href="${url}" target="_blank" class="autoLink">${url}</a>`
}
})
}

Array.from(document.querySelectorAll(".c-content")).forEach(a => { // .c-content 수정
if (!a.classList.contains("modded")) {
a.innerHTML = mod(a.innerHTML);
a.classList.add("modded");
}
})
}

document.addEventListener("DOMContentLoaded", function () {
autowrap()
});


.c-content만 본인의 댓글 형식에 맞게 수정하면 사용하실 수 있습니다.


추가된 유튜브 비디오를 감싸는 css는 https://marshall-ku.com/259에 자세히 적어놨습니다. 참고해주세요.


.youtubevid-wrapper {
min-width: 400px
}

.resvid {
position: relative;
width: 100%;
padding-bottom: 56.25%;
margin: auto
}



(function(){
  if (document.body.id === "tt-body-page" || document.body.id === "tt-body-guestbook") {
      setInterval(function() {
autowrap()
}, 500)
  }
}())


티스토리에선 답글이 달리거나 오래된 댓글을 불러오면 그 댓글들은 스크립트가 처리할 수 없으니, 500ms마다 해당 스크립트가 동작하도록 해놓으면 답글을 추가하거나, 이전 댓글을 불러와도 모두 스크립트가 처리합니다.



스크립트가 작동하지 않았을 때



스크립트가 작동했을 때