WindowEventHandlers.onhashchange

WindowEventHandlers 믹스인의 WindowEventHandlers.onhashchange 속성은

hashchange 이벤트를 처리하기 위한 event handler 입니다.

hashchange 이벤트는 윈도우의 해시가 변경되면 시작됩니다. ( Window.locationHTMLHyperlinkElementUtils.hash (en-US) 참조)

문법

event handler:

window.onhashchange = funcRef;

HTML event handler:

<body onhashchange="funcRef();">

event listener:

addEventListener()를 사용하여 이벤트 리스너 추가하기

window.addEventListener("hashchange", funcRef, false);

매개변수

funcRef

함수에 대한 참조.

예제

event handler 사용하기

This example uses an event handler (window.onhashchange) to check the new hash value whenever it changes. If it equals #cool-feature, the script logs a message to the console.

function locationHashChanged() {
  if (location.hash === '#cool-feature') {
    console.log("You're visiting a cool feature!");
  }
}

window.onhashchange = locationHashChanged;

Using an event listener

이 예제는 이벤트 리스너를 사용하여 해시가 변경 될 때마다 콘솔에 알림표시합니다.

function hashHandler() {
  console.log('The hash has changed!');
}

window.addEventListener('hashchange', hashHandler, false);

Overriding the hash

이 함수는 새로운 해시를 동적으로 설정하여 임의로 두 값 중 하나로 설정합니다.

function changeHash() {
  location.hash = (Math.random() > 0.5) ? 'location1' : 'location2';
}

hashchange 이벤트

hashchange 이벤트에는 다음과 같은 필드가 있습니다:

Field Type Description
newURL DOMString 탐색할 새로운 URL입니다.
oldURL DOMString 탐색했던 이전의 URL입니다.

제2의 해결책을 위한 event.newURL 와 event.oldURL

//let this snippet run before your hashchange event binding code
if(!window.HashChangeEvent)(function(){
  var lastURL=document.URL;
  window.addEventListener("hashchange",function(event){
    Object.defineProperty(event,"oldURL",{enumerable:true,configurable:true,value:lastURL});
    Object.defineProperty(event,"newURL",{enumerable:true,configurable:true,value:document.URL});
    lastURL=document.URL;
  });
}());

명세

Specification
HTML Standard
# event-hashchange
HTML Standard
# handler-window-onhashchange

브라우저 호환성

BCD tables only load in the browser

See also