자바 스크립트에서 페이지가 새로 고침되거나 새로 고침되는지 확인
누군가가 페이지를 새로 고치려고 할 때 확인하고 싶습니다.
예를 들어 페이지를 열면 아무 일도 일어나지 않지만 페이지를 새로 고치면 경고가 표시됩니다.
페이지가 실제로 다시로드되는지 확인하는 가장 좋은 방법은 대부분의 최신 브라우저에서 지원하는 탐색기 개체를 사용하는 것입니다.
Navigation Timing API를 사용합니다 .
//check for Navigation Timing API support
if (window.performance) {
console.info("window.performance works fine on this browser");
}
if (performance.navigation.type == 1) {
console.info( "This page is reloaded" );
} else {
console.info( "This page is not reloaded");
}
출처 : https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API
첫 번째 단계는 sessionStorage
미리 정의 된 값과 경고 사용자가 있는지 확인하는 것입니다.
if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');
두 번째 단계는 sessionStorage
어떤 값 으로 설정 하는 것입니다 (예 true
:) :
sessionStorage.setItem("is_reloaded", true);
페이지가 닫힐 때까지 세션 값이 유지되므로 사이트가있는 새 탭에서 페이지를 다시로드 한 경우에만 작동합니다. 재 장전 횟수도 같은 방식으로 유지할 수 있습니다.
새로운 표준 2018, 2019 (성능 탐색 타이밍)
window.performance.navigation
탐색 타이밍 레벨 2 스펙 에서는이 특성이 더 이상 사용되지 않습니다 . 대신 인터페이스를 사용하십시오 .PerformanceNavigationTiming
PerformanceNavigationTiming.type
이것은 실험적인 기술 입니다.
프로덕션 환경에서 사용하기 전에 브라우저 호환성 표를 주의 깊게 확인하십시오 .
2019-07-08 지원
type 읽기 전용 속성은 탐색 유형을 나타내는 문자열을 반환합니다. 값은 다음 중 하나 여야합니다.
탐색 — 링크를 클릭하거나 브라우저의 주소 표시 줄에 URL을 입력하거나 양식을 제출하거나 아래에 표시된 것처럼 reload 및 back_forward 이외의 스크립트 작업을 통해 초기화하여 탐색을 시작했습니다.
다시로드 — 탐색은 브라우저의 다시로드 작업 또는을 통해 이루어
location.reload()
집니다.back_forward — 탐색은 브라우저의 히스토리 탐색 조작을 통해 이루어집니다.
prerender — 탐색은 prerender 힌트에 의해 시작됩니다 .
이 속성은 읽기 전용입니다.
다음 예제는이 속성의 사용법을 보여줍니다.
function print_nav_timing_data() {
// Use getEntriesByType() to just get the "navigation" events
var perfEntries = performance.getEntriesByType("navigation");
for (var i=0; i < perfEntries.length; i++) {
console.log("= Navigation entry[" + i + "]");
var p = perfEntries[i];
// dom Properties
console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart));
console.log("DOM complete = " + p.domComplete);
console.log("DOM interactive = " + p.interactive);
// document load and unload time
console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart));
// other properties
console.log("type = " + p.type);
console.log("redirectCount = " + p.redirectCount);
}
}
누군가가 페이지를 처음 방문 할 때 쿠키를 저장하십시오. 쿠키를 새로 고칠 때 쿠키가 있는지 확인하고 쿠키가 있으면 경고하십시오.
function checkFirstVisit() {
if(document.cookie.indexOf('mycookie')==-1) {
// cookie doesn't exist, create it now
document.cookie = 'mycookie=1';
}
else {
// not first visit, so alert
alert('You refreshed!');
}
}
그리고 당신의 신체 태그에서 :
<body onload="checkFirstVisit()">
Javascript Detecting Page Refresh 에서 몇 가지 정보를 찾았습니다 . 그의 첫 번째 권장 사항은 페이지 새로 고침을 통해 저장되는 경향이있는 숨겨진 필드를 사용하는 것입니다.
function checkRefresh() {
if (document.refreshForm.visited.value == "") {
// This is a fresh page load
document.refreshForm.visited.value = "1";
// You may want to add code here special for
// fresh page loads
} else {
// This is a page refresh
// Insert code here representing what to do on
// a refresh
}
}
<html>
<body onLoad="JavaScript:checkRefresh();">
<form name="refreshForm">
<input type="hidden" name="visited" value="" />
</form>
</body>
</html>
만약
event.currentTarget.performance.navigation.type
보고
0 => 사용자가 방금 입력 한 URL
1 => 페이지 새로 고침
2 => 뒤로 버튼 클릭
I found some information here Javascript Detecting Page Refresh
function UnLoadWindow() {
return 'We strongly recommends NOT closing this window yet.'
}
window.onbeforeunload = UnLoadWindow;
I have wrote this function to check both methods using old window.performance.navigation
and new performance.getEntriesByType("navigation")
in same time:
function navigationType(){
var result;
var p;
if (window.performance.navigation) {
result=window.performance.navigation;
if (result==255){result=4} // 4 is my invention!
}
if (window.performance.getEntriesByType("navigation")){
p=window.performance.getEntriesByType("navigation")[0].type;
if (p=='navigate'){result=0}
if (p=='reload'){result=1}
if (p=='back_forward'){result=2}
if (p=='prerender'){result=3} //3 is my invention!
}
return result;
}
Result description:
0: clicking a link, Entering the URL in the browser's address bar, form submission, Clicking bookmark, initializing through a script operation.
1: Clicking the Reload button or using Location.reload()
2: Working with browswer history (Bakc and Forward).
3: prerendering activity like <link rel="prerender" href="//example.com/next-page.html">
4: any other method.
참고URL : https://stackoverflow.com/questions/5004978/check-if-page-gets-reloaded-or-refreshed-in-javascript
'IT story' 카테고리의 다른 글
새 파일이나 삭제 된 파일에 대해 gulp.watch가 트리거되지 않습니까? (0) | 2020.06.10 |
---|---|
JavaScript : 선택에 따라 양식 동작 속성 값을 변경하는 방법은 무엇입니까? (0) | 2020.06.10 |
mongoDB가 데이터를 저장하는 위치를 어떻게 알 수 있습니까? (0) | 2020.06.10 |
기존 프로젝트에 ASP.NET MVC5 ID 인증 추가 (0) | 2020.06.10 |
iPhone : 마지막 화면 터치 이후의 사용자 비 활동 / 유휴 시간 감지 (0) | 2020.06.10 |