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

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

    Browser security settings prevent people from modifying the displayed url directly. You could imagine the phishing vulnerabilities that would cause.

    Only reliable way to change the url without changing pages is to use an internal link or hash. e.g.: http://site.com/page.html becomes http://site.com/page.html#item1 . This technique is often used in hijax(AJAX + preserve history).

    When doing this I'll often just use links for the actions with the hash as the href, then add click events with jquery that use the requested hash to determine and delegate the action.

    I hope that sets you on the right path.

    0 讨论(0)
  • 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("#","");
    
    0 讨论(0)
提交回复
热议问题