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

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

    I've had success with:

    location.hash="myValue";
    

    It just adds #myValue to the current URL. If you need to trigger an event on page Load, you can use the same location.hash to check for the relevant value. Just remember to remove the # from the value returned by location.hash e.g.

    var articleId = window.location.hash.replace("#","");
    

提交回复
热议问题