Why browsers can't listen for popstate events

  1. you need to pushState and then fallback before you can enter the listening event of popstate
window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null
history.go(2);

if pushstate is not executed, it will not enter onpopstate if it is backed up directly. Why

Jul.06,2022

browser security policy restrictions, it is impossible for you to get the user's own history


https://developer.mozilla.org...
mdn wrote
note that calling history.pushState () or history.replaceState () will not trigger the popstate event. This event is triggered only when a browser action is made, such as when the user clicks the browser's fallback button (or calls history.back () or history.forward () method in Javascript code)

Menu