Routing

History

Push State / Replace State

  • The url will change, but the html doesn't be changed

pushState(state, unused, url)

  • state: put the object data to this page

  • unused: always give empty string is okay

  • url: for changing url to the browser without going to new page

  • replace vs push: create new url to the history or not


window.history.replaceState(
    {test:3},
    "",
    "https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState?diu=3"
);

// get back the state
console.log(history.state);
// {test:3}

Location

Information

  • host: the hostname + port number

  • hostname

  • pathname: /xxx...

  • search: ?...., used to assign additional data to the page and can be displayed to the user

  • hash: #..., represent the fragment section of the page and change the hash without full page loading

  • href : the full url

Method

// replace the topmost history stack
window.location.replace("...")
// push the top history into history stack
window.location.href = "..."

// xxx.com?campaign=instagram&popular=true
let params = new URLSearchParams(location.search);
params.get("campaign"); // "instagram"
params.get("popular"); // "true"
params.toString(); // "campaign=instagram&popular=true",

Last updated

Was this helpful?