-
[Javascipt] Clipboard API 사용JavaScript 2023. 3. 4. 17:50
갈틱폰 사이트를 보면 방 입장시 브라우저 표시줄의 주소가 깔끔하다는 것을 볼 수 있다.
로비에서 초대 버튼을 누르면 아래와 같이 쿼리스트링을 통해 채널번호를 명시해둔 걸 볼 수 있다. 초대 링크를 붙여넣기 하면 /lobby로 이동하게 된다.
(생각해보니 방송 스트리밍 시 주소창을 보고 방의 링크를 알 수 있는 상황이 생길 수 있는 듯)
// 초대 링크 https://garticphone.com/ko/?c=채널번호 // 입장시 https://garticphone.com/ko/lobby
나는 Next.js를 사용하였기에 useRouter의 push와 replace 메소드 두번째 인수인 as를 통해 브라우저 URL 표시줄에 표시할 경로를 명시할 수 있어 /room에 입장하면 useEffect를 통해 표시줄에는 쿼리스트링을 숨겨두었다.
const router = useRouter(); router.replace( { pathname: "/room", query: { c: roomId, }, }, "/room" );
이제 이 페이지에 들어올 수 있는 초대 버튼을 만들어야 한다. 이때 Clipboard API를 사용할 수 있다.
텍스트를 복사하기 위해 navigator.clipboard.writeText(텍스트)를 호출하기만 하면 된다.
나는 원래의 주소인 채널번호를 넣어 이 채널번호의 룸으로 들어오겠끔 하였다.
const handleInviteClick = () => { navigator.clipboard.writeText(`${window.location.href}?c=${roomId}`); }; <button onClick={handleInviteClick}>초대</button>
참고로 Clipboard API는 local이나 https 환경에서만 동작한다고 한다.
반응형'JavaScript' 카테고리의 다른 글
[JavaScript] 여러 request 처리하기 with RTK Query (0) 2023.05.08 [JavaScript] Number + (undefined, null, false)와 NaN (0) 2023.04.25 [JavaScript] 배열 숫자 채우기 (0) 2023.02.10 [JavaScript] RTK Query: Automated Re-fetching (1) 2023.01.06 [JavaScript] 특정 요소에 따른 스크롤 자동 조정 : scrollIntoView() (0) 2023.01.03