JavaScript에서 URL이 변경되었는지 어떻게 확인합니까? 예를 들어 AJAX를 사용하는 GitHub와 같은 웹 사이트는 # 기호 뒤에 페이지 정보를 추가하여 페이지를 다시로드하지 않고 고유 한 URL을 만듭니다. 이 URL이 변경되는지 감지하는 가장 좋은 방법은 무엇입니까?
- 는 IS
onload
이벤트가 다시 호출? - URL에 대한 이벤트 핸들러가 있습니까?
- 또는 변경 사항을 감지하기 위해 URL을 1 초마다 확인해야합니까?
답변
최신 브라우저 (IE8 +, FF3.6 +, Chrome)에서는에서 hashchange
이벤트를 들을 수 있습니다 window
.
일부 구형 브라우저에서는 계속 확인하는 타이머가 필요합니다 location.hash
. jQuery를 사용하는 경우 정확히 수행 하는 플러그인 이 있습니다.
답변
locationchange
이벤트 리스너 를 추가하고 싶었습니다 . 아래 수정 후에는 다음과 같이 할 수 있습니다.
window.addEventListener('locationchange', function(){
console.log('location changed!');
})
대조적으로, window.addEventListener('hashchange',()=>{})
URL에서 해시 태그 뒤에있는 부분이 변경되고 window.addEventListener('popstate',()=>{})
항상 작동하지 않는 경우에만 실행됩니다 .
Christian의 답변 과 비슷한이 수정은 기록 개체를 수정하여 일부 기능을 추가합니다.
기본적으로 popstate
이벤트가 있지만 pushstate
및에 대한 이벤트가 없습니다 replacestate
.
이렇게하면이 세 가지 기능이 수정되어 모든 사용자 locationchange
가 사용할 사용자 지정 이벤트 pushstate
와 해당 replacestate
이벤트를 사용하려는 경우 이벤트가 발생합니다.
/* These are the modifications: */
history.pushState = ( f => function pushState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('pushstate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.pushState);
history.replaceState = ( f => function replaceState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('replacestate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.replaceState);
window.addEventListener('popstate',()=>{
window.dispatchEvent(new Event('locationchange'))
});
답변
이 코드를 사용하십시오
window.onhashchange = function() {
//code
}
jQuery와 함께
$(window).bind('hashchange', function() {
//code
});
답변
약간의 연구 후에 편집하십시오.
어떻게 든 모질라 문서에있는 문서에 바보가 된 것 같습니다. popstate
이벤트 (및 콜백 함수 onpopstate
)하는 트리거되지 때마다 pushState()
또는 replaceState()
코드라고합니다. 따라서 원래 답변은 모든 경우에 적용되지 않습니다.
그러나 @ alpha123에 따라 함수 를 원숭이 패치하여 이를 우회하는 방법이 있습니다 .
var pushState = history.pushState;
history.pushState = function () {
pushState.apply(history, arguments);
fireEvents('pushState', arguments); // Some event-handling function
};
원래 답변
이 질문의 제목이 ” URL 변경을 감지하는 방법 “이라는 대답을 감안할 때 해시 앵커뿐만 아니라 전체 경로가 언제 변경되는지 알고 싶은 경우 popstate
이벤트를 수신 할 수 있다는 것입니다 .
window.onpopstate = function(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
현재 (2017 년 1 월) 전 세계 브라우저의 92 %에서 popstate 가 지원 됩니다.
답변
jquery (및 플러그인)를 사용하면 할 수 있습니다
$(window).bind('hashchange', function() {
/* things */
});
http://benalman.com/projects/jquery-hashchange-plugin/
그렇지 않으면, setInterval을 사용하고 해시 이벤트 (window.location.hash)의 변경을 확인해야합니다.
최신 정보! 간단한 초안
function hashHandler(){
this.oldHash = window.location.hash;
this.Check;
var that = this;
var detect = function(){
if(that.oldHash!=window.location.hash){
alert("HASH CHANGED - new has" + window.location.hash);
that.oldHash = window.location.hash;
}
};
this.Check = setInterval(function(){ detect() }, 100);
}
var hashDetection = new hashHandler();
답변
해시 변경 이벤트 리스너를 추가하십시오!
window.addEventListener('hashchange', function(e){console.log('hash changed')});
또는 모든 URL 변경 사항을 청취하려면 다음을 수행하십시오.
window.addEventListener('popstate', function(e){console.log('url changed')});
window.onhashchange에는 한 가지만 존재할 수 있으며 다른 사람의 코드를 덮어 쓸 수 있기 때문에 아래 코드와 같은 것이 좋습니다.
// Bad code example
window.onhashchange = function() {
// Code that overwrites whatever was previously in window.onhashchange
}
답변
이 솔루션은 저에게 효과적이었습니다.
var oldURL = "";
var currentURL = window.location.href;
function checkURLchange(currentURL){
if(currentURL != oldURL){
alert("url changed!");
oldURL = currentURL;
}
oldURL = window.location.href;
setInterval(function() {
checkURLchange(window.location.href);
}, 1000);
}
checkURLchange();
