Javascript 에서 uirl 변경되었습니까 경우 어떻게 확인할 수 있습니까? 예를 들어, 아약스, 깃허브 등 웹 페이지 정보 # 기호를 사용하는 고유 URL 생성 후 거역한다면 덮어쓰기/추가 리로드하지 않고 페이지. 이 경우 uirl 변화를 감지할 수 있는 최선의 방법은 무엇입니까?
최근의 브라우저에서 (IE8+, FF3.6+, 구글 크롬), '이벤트' 윈도 '듣기' 하슈란제 됩니다.
일부 오래된 브라우저 있는 타이머가 로카션.하시 지속적으로 점검 '' 합니다. # 39, re you& jquery 가 사용하는 경우, a href = " >;;; http://benalman.com/projects/jquery-hashchange-plugin/ " < plugin< /a>. 정확히 않는 iqn.
Jquery (및 플러그-인을) 함께 할 수 있습니다.
$(window).bind('hashchange', function() {
/* things */
});
http://benalman.com/projects/jquery-hashchange-plugin/
그렇지 않으면 그러하너라 사용해야 할 때와 변화가 해시보다 이벤트 (빈다우드로카션.하시) 및 확인할지 setInterval
업데이트! 간단한 구배하는
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();
저는 그동안 의해 필리핀 붽뎄 mizilla docs 에 존재하는 그 어떤 것으로 보인다. 이 '포프스타트' 이벤트 (및 그 콜백 함수 '롱포프스타트') 는 [not 트리거됨] (https://stackoverflow.com/a/10947321/322253) '또는' () '이 레프리스국가 푸시국가 때마다' () 라는 코드. 따라서 기존 오토메이티드 모든 경우에 해당되지 않습니다.
그러나 이를 피할 방법이 [몽키 패칭 기능에 따라 @alpha123] (https://stackoverflow.com/a/10419974/322253):
var pushState = history.pushState;
history.pushState = function () {
pushState.apply(history, arguments);
fireEvents('pushState', arguments); // Some event-handling function
};
제목 " 점을 감안하면 이 질문은, , uirl change*&quo 탐지합니다 방법 그 때 알고 싶을 때, 전체 경로 변경 (및 아니라 해시보다 앵커) 의 도래하도록하려하는 들을 수 있다 '포프스타트' 이벤트:
window.onpopstate = function(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
현재 (1월 2017년) 에서 92% 좁히어 가 [포프스타트 대한 지원 브라우저] [2] 전세계적이며.
[2]: http://caniuse.com/ # 검색 = 포프스타트
내가 갖고 싶은 것은 '수' 로카션창레 이벤트 리스너를 추가합니다. 이를 통해 이 같은 수정, we can do
window.addEventListener('locationchange', function(){
console.log('location changed!');
})
반면 '빈다우드라데벤트리스트너 (& # 39,, # 39 hashchange& > () = {})' 만 볼지옥으로 부품의 경우 url 에 해시태그 변경되고, 후에 '빈다우드라데벤트리스트너 (& # 39,, # 39 popstate& > () = {})', t # 39 doesn& 항상 작동합니까.
이 수정, 유사한 Christian& # 39 의 오토메이티드, 수정되므로 객체에는 몇 가지 기능을 추가할 수 있다.
이 모든 사용자 정의 '' 이 세 가지 기능을 제공하므로 수정되므로 불지옥의 로카션창레 사용할 수 있습니다, 또한 '이벤트' 이벤트 '와' 레프리스국가 푸시국가 사용하려면 그.
/* 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.addEventListener('hashchange', function(e){console.log('hash changed')});
또는 듣고 모든 uirl 변경:
window.addEventListener('popstate', function(e){console.log('url changed')});
이 같은 일이 있기 때문에 존재할 수 있는 것보다 더 나은 아래 코드는 오직 한가지만 빈다우스온하슈란제 및 you& # 39, ll, 코드 s # 39 else& 가능성이 높아 덮어쓰기는 누군가.
// 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();
비록 이 오래된 질문, 위치 표시줄에는 프로젝트는 매우 유용합니다.
var LocationBar = require("location-bar");
var locationBar = new LocationBar();
// listen to all changes to the location bar
locationBar.onChange(function (path) {
console.log("the current url is", path);
});
// listen to a specific change to location bar
// e.g. Backbone builds on top of this method to implement
// it's simple parametrized Backbone.Router
locationBar.route(/some\-regex/, function () {
// only called when the current url matches the regex
});
locationBar.start({
pushState: true
});
// update the address bar and add a new entry in browsers history
locationBar.update("/some/url?param=123");
// update the address bar but don't add the entry in history
locationBar.update("/some/url", {replace: true});
// update the address bar and call the `change` callback
locationBar.update("/some/url", {trigger: true});
듣고 uirl 변경, 아래 참조:
window.onpopstate = function(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
이 스타일을 사용할 경우 일부 특정 조건을 리스너에 정지점을 / 제거 후 수 있는 것이 특징이다.
window.addEventListener('popstate', function(e) {
console.log('url changed')
});
Look at 언로드할 기능을 포함한다. 모든 것을 처리한다.
https://api.jquery.com/unload/
>. 언로드 이벤트 페이지에서 사용자가 빼냅니다 송신됩니다 요소점 창으로 이동합니다. 이 많은 것들 중 하나를 의미할 수 있다. 할 수 있는 링크를 클릭하여 사용자 페이지, 또는 새로운 URL 주소 표시줄에 남겨두십시오 입력되었는지. 앞뒤 踰꾪듉 트리거됩니다 event. 브라우저 창 닫기와 이벤트 트리거됩니다 원인이 된다. 이벤트 페이지 리로드하려면 언로드할 처음 만드는 것이라고 한다.
$(window).unload(
function(event) {
alert("navigating");
}
);
같은 문제를 겪고 있는 수행하는 동안, 나는 조금 크롬 확장명은 애디션널 문제: 변경하십시오 URL. 서피스뿐 아니라 때로는 페이지
예를 들어, 페이스북, & # 39 Home& 그냥 documentum. 홈_페이지 클릭한 후, # 39. 버튼를. 그러나 너희는 페이지를 다시 로드하십시오 uirl won& # 39, t change (한 페이지짜리 app 스타일).
그래서 우리는 핵 물질, 우리는 그 때 99% 의 웹 사이트를 통해 얻을 수 있는 시간이 프레임워크와도 각, 이벤트 등 브루 상술합니다.
, 그러나 내 경우 (in 바닐라 JS), 크롬 확장명은 듣고 난 이미 각 " change" 수 있는 이벤트가 트리거하는, 페이지 url 을 이용한 경우도 있다고 하지만, 일반적으로 포착됨 변경일 doesn& # 39, t.
내 집에서 해결책은 다음과 같습니다.
listen(window.history.length);
var oldLength = -1;
function listen(currentLength) {
if (currentLength != oldLength) {
// Do your stuff here
}
oldLength = window.history.length;
setTimeout(function () {
listen(window.history.length);
}, 1000);
}
그래서 기본적으로 윈도우 레오네케르트 솔루션을 적용할 경우, 역사, 페이지 한 페이지 바뀌는 변화를 app.
하지만 내가 찾은 것은 깨끗한 솔루션이므로 고려할 때 우리는 로켓 사이언스 미디어만을 확인 되지 않은 것은 더 큰 정수 또는 전체 객체에는 임무야, DOM.
여기에서 그 아래 그때그들은 (이전 javascript 로 구문 (no 화살표 기능, 지원 IE 10): https://stackoverflow.com/a/52809105/9168962
(function() {
if (typeof window.CustomEvent === "function") return false; // If not IE
function CustomEvent(event, params) {
params = params || {bubbles: false, cancelable: false, detail: null};
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
window.CustomEvent = CustomEvent;
})();
(function() {
history.pushState = function (f) {
return function pushState() {
var ret = f.apply(this, arguments);
window.dispatchEvent(new CustomEvent("pushState"));
window.dispatchEvent(new CustomEvent("locationchange"));
return ret;
};
}(history.pushState);
history.replaceState = function (f) {
return function replaceState() {
var ret = f.apply(this, arguments);
window.dispatchEvent(new CustomEvent("replaceState"));
window.dispatchEvent(new CustomEvent("locationchange"));
return ret;
};
}(history.replaceState);
window.addEventListener("popstate", function() {
window.dispatchEvent(new CustomEvent("locationchange"));
});
})();