개발자의 오르막

SNS 공유하기 ( Spring Boot, Thymeleaf ) 본문

SpringFrameWork/SpringBoot

SNS 공유하기 ( Spring Boot, Thymeleaf )

계단 2020. 2. 4. 14:30

기존 게시물들의 SNS 공유하기 기능을 구현하는 것에 있어서 정말 많은 글들이 있었지만

테스트하기 어려웠고, 페이스북, 카카오스토리 의 캐쉬 삭제 까지 신경쓰느라

스트레스 받았던 기능이다.

 

SNS 공유는 페이스북, 트위터, 카카오스토리 이며, Javascript 로 구현하였다.

 

# SNS 공유하기, 자바스크립트

 

function snsShare(snsName, link, title) {

	if (title === null) return false;

	var snsPopUp;
	var _width = '500';
	var _height = '450';
	var _left = Math.ceil(( window.screen.width - _width )/2);
	var _top = Math.ceil(( window.screen.height - _height )/2);

	switch(snsName){
		case 'facebook':
			snsPopUp = window.open("http://www.facebook.com/sharer/sharer.php?u=" + link, '', 'width='+ _width +', height='+ _height +', left=' + _left + ', top='+ _top);
			break;

		case 'twitter' :
			snsPopUp = window.open("http://twitter.com/intent/tweet?url=" + link + "&text=" + title, '', 'width='+ _width +', height='+ _height +', left=' + _left + ', top='+ _top);
			break;

		case 'kakao' :
			snsPopUp = window.open("https://story.kakao.com/share?url=" + link, '', 'width='+ _width +', height='+ _height +', left=' + _left + ', top='+ _top);
			break;

		case 'addurl' :
			var dummy = document.createElement("textarea");
			document.body.appendChild(dummy);
			dummy.value = link;
			dummy.select();
			document.execCommand("copy");
			document.body.removeChild(dummy);
			oneBtnModal("URL이 클립보드에 복사되었습니다.");
			break;
	}
}

 

 - 원래 기존의 url 에 스크랩하고자 하는 link를 붙이면 페이지가 넘어가면서 공유하기 기능이 되지만,

   저는 팝업 형태로 SNS 공유 창을 띄우기 위해 위와 같은 snsPopup 을 사용하였다.

 

 - case 는 각각의 sns 버튼을 누를 때의 value 값을 기준으로 분류하였고, addurl 은 현재 사이트 링크

   복사 기능이다.

 

 

# SNS 공유하기 기능 테스트

 - 가장 힘든 부분이 바로 SNS 공유하기 기능 테스트이다.

 

 - 공유할 때 컨텐츠 구성을 우리는 meta 태그로 해야 한다.

   이때 접하게 되는 개념이 OG 프로토콜이다.

 

 * 주의 : 로컬 또는 개발 서버 ( VPN ) 에서는 타 사이트가 접근이 불가함으로 링크나 컨텐츠를

            구성할 수 없다.

 

 

# OG 프로토콜

 - OG ( Open Graph ) 프로토콜은 쉽게 말해 타 사이트가 크롤링이나 우리 사이트의 정보를 

   가져오자고 할 때, 필요한 약속이다.  ( https://ogp.me/ )

   우리는 meta 태그를 통해 타 사이트에서 가져갈 데이터를 정의하고, 그러면 타 사이트에서는 우리의

   사이트 전체를 찾아보는 것이 아니라 meta 태그만 찾아 데이터를 가져가게 된다.

 

   즉, SNS 공유하기에 사용될 이미지나 제목, 설명 등을 메타태그로 정의해야 컨텐츠를 구성할 수 있다.

 

 

 - OG 프로토콜 기본 메타태그

<head>
    <meta property="og:url" content="https://devtalk.kakao.com/">
    <meta property="og:title" content="Kakao DevTalk_">  
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://devtalk.kakao.com/images/devtalk_.png">
    <meta property="og:description" content="카카오 데브톡. 카카오 플랫폼 서비스 관련 질문 및 답변을 올리는 개발자 커뮤니티 사이트입니다.">
    <meta name="description" content="카카오 데브톡. 카카오 플랫폼 서비스 관련 질문 및 답변을 올리는 개발자 커뮤니티 사이트입니다.">
    <meta name="keywords" content="데브톡,devtalk,카카오,디벨로퍼스,개발자,API,플랫폼">
</head>

 

 

# meta 태그 자바스크립트로 가능?

 

 - 이 부분이 가장 애먹었다. 각 스크랩을 하기 위해서는 위의 메타 태그를 가공해야 한다.

   예를 들어 이미지와 제목, 설명을 그 게시물의 데이터로 반영해야 하는 것이다.

   

   구글링을 하게 되면 이런 부분들을 Javascript 로 동적 제어를 하라고 나와 있다.

var url = 'http://marsland.tistory.com';
var title = '삽질하는 프로그래머 통통만두';
var description = '삽질하는 프로그래머 통통만두의 퐌타스틱한 삽질기';
var imgUrl = 'https://t1.daumcdn.net/cfile/tistory/9983C83C5AFB757A18';


if( ! $('meta[property="og:url"').attr('content') ) { 
	$('head').append( StringTool.format('<meta property="og:url" content="{0}" />', url) ); 
} 

if( ! $('meta[property="og:type"').attr('content') ) { 
	$('head').append( StringTool.format('<meta property="og:type" content="{0}" />', 'article') ); 
} 

if( ! $('meta[property="og:title"').attr('content') ) {
	$('head').append( StringTool.format('<meta property="og:title" content="{0}" />', title) );
} 

if( ! $('meta[property="og:description"').attr('content') ) { 
	$('head').append( StringTool.format('<meta property="og:description" content="{0}" />', description) ); 
} 

if( ! $('meta[property="og:image"').attr('content') ) { 
	$('head').append( StringTool.format('<meta property="og:image" content="{0}" />', imgUrl) ); 
}

var linkUrl = window.location.href; 
window.open( 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(linkUrl) );

   - 출처 : https://marsland.tistory.com/470

 

 그러나 테스트를 해봤지만 meta 태그는 static으로 javascript 를 사용하기 전에 긁고 끝나기 때문에

 반영이 안된다는 답변도 있었다.

 

출처 : https://devtalk.kakao.com/t/topic/95101

 

 따라서 meta 태그를 html 태그로 쓰기 위해 타임리프 문법으로 사용했다.

 

 

 

# Thymeleaf 문법을 사용한 og meta 태그

 

<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta property="og:site_name" content="" />
<meta property="article:author" content="" />
<meta property="og:title" th:content="${dto.title ne null and dto.title ne '' ? dto.title : ''}" />
<meta property="og:description" content="" />
<meta property="og:url" th:content="${#httpServletRequest.requestURL}" />
<meta property="og:image" id="snsImage" />
<meta property="og:type" content="website" />
<meta property="fb:app_id" content="" />

 

 

 

# 스크랩 캐쉬 삭제

 

 - SNS 공유하기에 사용되는 이미지를 테스트하기 위해 우리는 운영서버에서 테스트가 가능하다.

   그러나 운영을 배포한다고 해도, 이게 즉각적으로 반영되지 않는다. 이유는 우리의 스크랩 이미지는

   페이스북, 카카오 스토리에서 띄워주고 있기 때문에 그쪽 캐쉬를 삭제하지 않는 한 즉각 반영되지

   않는다.

 

 - 페이스북 공유하기 디버거 : https://developers.facebook.com/tools/debug/

 

공유 디버거 - Facebook for Developers

공유 디버거를 사용하면 Facebook에 공유될 때 콘텐츠가 표시되는 모습을 미리 보거나 오픈 그래프 태그를 사용하여 문제를 디버깅할 수 있습니다. 이 도구를 사용하려면 Facebook에 로그인하세요. 로그인

developers.facebook.com

 - 카카오 캐시 삭제 : https://developers.kakao.com/docs/cache 

 

카카오계정 로그인

여기를 눌러 링크를 확인하세요.

accounts.kakao.com

 

 이 두군데에서 캐쉬를 삭제하고, 다시 테스트하고를 반복해야 한다.

 

 

 - 카카오 스크랩 관련 문의 게시판

 

https://devtalk.kakao.com/c/scrap

 

Kakao DevTalk_

카카오 데브톡. 카카오 플랫폼 서비스 관련 질문 및 답변을 올리는 개발자 커뮤니티 사이트입니다.

devtalk.kakao.com

 

 

 

Comments