JavaScript
[JavaScript] 페이지에 머무른 시간 기록하기
teamnova
2025. 5. 4. 18:39
728x90
안녕하세요,
오늘은 한 페이지에 머무른 시간을 기록하는 예제를 만들어 보도록 하겠습니다.
이번 예제에서는 서버를 활용하지 않기 때문에 localStorage에 저장해보도록 하겠습니다.
새로고침 또는 창 닫기 를 하는 시점에 머물렀던 시간이 기록되게 됩니다.
예제 코드 입니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>페이지 머문 시간 기록기</title>
</head>
<body>
<h1>이 페이지에 머문 시간을 localStorage에 저장합니다.</h1>
<p id="output">이전 머문 시간: <span id="lastTime">로딩 중...</span>초</p>
<script>
const startTime = Date.now();
// 기존에 저장된 값 보여주기
const lastTime = localStorage.getItem('lastTimeSpent');
document.getElementById('lastTime').textContent = lastTime ? lastTime : '없음';
window.addEventListener('beforeunload', () => {
const endTime = Date.now();
const timeSpent = Math.round((endTime - startTime) / 1000); // 초 단위
// localStorage에 저장
localStorage.setItem('lastTimeSpent', timeSpent);
});
</script>
</body>
</html>
실행 후 새로고침 한 화면입니다.

개발자 도구 > Application > Storage > Local Storage 클릭 시 아래와 같이 저장된 정보를 확인할 수 있습니다.
