Window: sự kiện hashchange

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).

This event does not fire when the hash is modified using history.pushState() or history.replaceState().

Cú pháp

Sử dụng tên sự kiện trong các phương thức như addEventListener(), hoặc thiết lập thuộc tính trình xử lý sự kiện.

js
addEventListener("hashchange", (event) => { })

onhashchange = (event) => { }

Kiểu sự kiện

A HashChangeEvent. Inherits from Event.

Event HashChangeEvent

Event properties

HashChangeEvent.newURL Read only

A string representing the new URL the window is navigating to.

HashChangeEvent.oldURL Read only

A string representing the previous URL from which the window was navigated.

Event handler aliases

In addition to the Window interface, the event handler property onhashchange is also available on the following targets:

Ví dụ

You can use the hashchange event in an addEventListener method:

js
window.addEventListener("hashchange", () => {
  console.log("The hash has changed!");
});

Or use the onhashchange event handler property:

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

window.onhashchange = locationHashChanged;

Đặc tả kỹ thuật

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

Tính tương thích trên trình duyệt

Xem thêm