Change the URL in the browser without loading the new page using JavaScript

后端 未结 14 2222
忘掉有多难
忘掉有多难 2020-11-22 02:02

How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then

14条回答
  •  你的背包
    2020-11-22 02:41

    window.location.href contains the current URL. You can read from it, you can append to it, and you can replace it, which may cause a page reload.

    If, as it sounds like, you want to record javascript state in the URL so it can be bookmarked, without reloading the page, append it to the current URL after a # and have a piece of javascript triggered by the onload event parse the current URL to see if it contains saved state.

    If you use a ? instead of a #, you will force a reload of the page, but since you will parse the saved state on load this may not actually be a problem; and this will make the forward and back buttons work correctly as well.

提交回复
热议问题