JavaScript에서 페이지가 새로고침 또는 새로고침되는지 확인합니다.
다른 사람이 페이지를 새로 고치려고 할 때 확인하고 싶어요.
예를 들어 페이지를 열면 아무 일도 일어나지 않지만 페이지를 새로 고치면 경고가 표시됩니다.
⚠️⚠️⚠️window.performance.navigation.type
권장되지 않습니다.「 」의 답변을 참조해 주세요.
페이지가 실제로 새로고침되었음을 알 수 있는 더 좋은 방법은 대부분의 최신 브라우저에서 지원되는 네비게이터 개체를 사용하는 것입니다.
Navigation Timing API를 사용합니다.
//check for Navigation Timing API support
if (window.performance) {
console.info("window.performance works fine on this browser");
}
console.info(performance.navigation.type);
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
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
새로운 표준 2018-now (PerformanceNavigationTiming)
window.performance.navigation
속성은 내비게이션 타이밍 레벨 2 사양에서는 사용되지 않습니다.대신 인터페이스를 사용하십시오.
PerformanceNavigationTiming.type
이것은 실험적인 기술입니다.
운영 환경에서 사용하기 전에 브라우저 호환성 표를 주의 깊게 확인하십시오.
JavaScript에서 페이지가 새로고침 또는 새로고침되는지 확인합니다.
const pageAccessedByReload = (
(window.performance.navigation && window.performance.navigation.type === 1) ||
window.performance
.getEntriesByType('navigation')
.map((nav) => nav.type)
.includes('reload')
);
alert(pageAccessedByReload);
2021-11-09 지원
type read-only 속성은 탐색 유형을 나타내는 문자열을 반환합니다.값은 다음 중 하나여야 합니다.
navigate : 링크를 클릭하거나 브라우저 주소창에 URL을 입력하거나 폼을 제출하거나 다음과 같이 reload 및 back_forward 이외의 스크립트 조작을 통해 초기화하는 것으로 네비게이션이 시작됩니다.
reload : 브라우저 새로고침 조작 또는 네비게이션이 이루어집니다.
back_forward : 브라우저 이력 트래버설 조작을 통해 네비게이션이 이루어집니다.
preender : 프리렌더힌트에 의해 네비게이션이 시작됩니다.
이 속성은 읽기 전용입니다.
다음은 이 속성의 사용 예를 보여 줍니다.
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);
}
}
첫 번째 단계는 미리 정의된 값이 있는지 및 해당 값이 존재하는지 확인하는 것입니다.
if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');
두 번째 단계는 특정 값으로 설정하는 것입니다(예:true
sessionStorage.setItem("is_reloaded", true);
페이지가 닫힐 때까지 유지되는 세션 값은 사이트가 있는 새 탭에서 페이지가 새로고침된 경우에만 작동합니다.새로고침 카운트를 동일하게 유지할 수도 있습니다.
사용자가 처음 페이지를 방문했을 때 쿠키를 저장합니다.새로 고침 시 쿠키가 있는지 확인하고 쿠키가 있으면 경고합니다.
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()">
방법을 모두 이 했습니다.window.performance.navigation
및 신규performance.getEntriesByType("navigation")
동시에:
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;
}
결과 설명:
0: 링크 클릭, 브라우저 주소창에 URL 입력, 폼 제출, 북마크 클릭, 스크립트 조작으로 초기화.
1: [Reload]버튼을 클릭하거나Location.reload()
2: 브라우저 기록 작업(Bakc 및 Forward)
3: 프리렌더링 액티비티는 다음과 같습니다.<link rel="prerender" href="//example.com/next-page.html">
4: 기타 방법
한다면
event.currentTarget.performance.navigation.type
돌아온다
0 = > 사용자가 URL을 입력했습니다.
1 = > 페이지 새로고침
2 = > Back(뒤로)
여기서 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>
Javascript Detecting Page Refresh에서 몇 가지 정보를 찾았습니다.
function UnLoadWindow() {
return 'We strongly recommends NOT closing this window yet.'
}
window.onbeforeunload = UnLoadWindow;
if(sessionStorage.reload) {
sessionStorage.reload = true;
// optionnal
setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
sessionStorage.setItem('reload', false);
}
다음은 거의 모든 브라우저에서 지원되는 방법입니다.
if (sessionStorage.getItem('reloaded') != null) {
console.log('page was reloaded');
} else {
console.log('page was not reloaded');
}
sessionStorage.setItem('reloaded', 'yes'); // could be anything
SessionStorage를 사용하여 페이지가 처음 열렸는지 또는 새로 고쳐졌는지 확인합니다.
콘솔에 다음 스크립트를 추가합니다.
window.addEventListener("beforeunload", function(event) {
console.log("The page is redirecting")
debugger;
});
<script>
var currpage = window.location.href;
var lasturl = sessionStorage.getItem("last_url");
if(lasturl == null || lasturl.length === 0 || currpage !== lasturl ){
sessionStorage.setItem("last_url", currpage);
alert("New page loaded");
}else{
alert("Refreshed Page");
}
</script>
document.addEventListener("keydown", (e)=>{
if (e.keyCode === 116) {
e.preventDefault();
// your code here
// var r = confirm("Reload!");
// if (r == true)
// window.location.reload();
}
})
- 여기서는 이벤트 청취자 'keydown'을 사용했는데, 이는 브라우저에서는 'keypress'를 위한 F1 - F12 키를 사용할 수 없기 때문입니다.
- 116은 'F5'의 키코드입니다.여기를 체크해 주세요
- 'prevent Default()'는 누른 키의 기본 기능을 중지합니다.여기서 F5를 누르면 직접 새로 고침이 중지됩니다.
- 그런 다음 코드를 추가합니다.
- 경고가 확인되면 'location.reload()'가 페이지를 새로고침합니다.
언급URL : https://stackoverflow.com/questions/5004978/check-if-page-gets-reloaded-or-refreshed-in-javascript
'programing' 카테고리의 다른 글
jQuery는 요소와 관련된 모든 CSS 스타일을 가져올 수 있습니까? (0) | 2022.11.22 |
---|---|
스크롤 후 요소가 표시되는지 확인하는 방법 (0) | 2022.11.22 |
Java에서의 MySQL 데이터 시간 및 타임스탬프 처리 (0) | 2022.11.22 |
MySQL의 테이블 필드에 인덱스가 있는지 확인하는 방법 (0) | 2022.11.22 |
JavaScript 변수 존재 여부 확인(정의/초기화) (0) | 2022.11.22 |