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

后端 未结 14 2230
忘掉有多难
忘掉有多难 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:34

    If you want it to work in browsers that don't support history.pushState and history.popState yet, the "old" way is to set the fragment identifier, which won't cause a page reload.

    The basic idea is to set the window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don't support onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval for example) and update the page. You will also need to check the hash value on page load to set up the initial content.

    If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.

    One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.

提交回复
热议问题