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

后端 未结 14 2244
忘掉有多难
忘掉有多难 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.

    0 讨论(0)
  • 2020-11-22 02:35

    jQuery has a great plugin for changing browsers' URL, called jQuery-pusher.

    JavaScript pushState and jQuery could be used together, like:

    history.pushState(null, null, $(this).attr('href'));

    Example:

    $('a').click(function (event) {
    
      // Prevent default click action
      event.preventDefault();     
    
      // Detect if pushState is available
      if(history.pushState) {
        history.pushState(null, null, $(this).attr('href'));
      }
      return false;
    });
    

    Using only JavaScript history.pushState(), which changes the referrer, that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.

    Example:

    window.history.pushState("object", "Your New Title", "/new-url");

    The pushState() method:

    pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let's examine each of these three parameters in more detail:

    1. state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.

      The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.

    2. title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.

    3. URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.

    0 讨论(0)
  • 2020-11-22 02:36

    Facebook's photo gallery does this using a #hash in the URL. Here are some example URLs:

    Before clicking 'next':

    /photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507
    

    After clicking 'next':

    /photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507#!/photo.php?fbid=496435457507&set=a.218088072507.133423.681812507&pid=5887085&id=681812507
    

    Note the hash-bang (#!) immediately followed by the new URL.

    0 讨论(0)
  • 2020-11-22 02:36

    A more simple answer i present,

    window.history.pushState(null, null, "/abc")
    

    this will add /abc after the domain name in the browser URL. Just copy this code and paste it in the browser console and see the URL changing to "https://stackoverflow.com/abc"

    0 讨论(0)
  • 2020-11-22 02:36

    my code is:

    //change address bar
    function setLocation(curLoc){
        try {
            history.pushState(null, null, curLoc);
            return false;
        } catch(e) {}
            location.hash = '#' + curLoc;
    }
    

    and action:

    setLocation('http://example.com/your-url-here');
    

    and example

    $(document).ready(function(){
        $('nav li a').on('click', function(){
            if($(this).hasClass('active')) {
    
            } else {
                setLocation($(this).attr('href'));
            }
                return false;
        });
    });
    

    That's all :)

    0 讨论(0)
  • 2020-11-22 02:37

    There is a Yahoo YUI component (Browser History Manager) which can handle this: http://developer.yahoo.com/yui/history/

    0 讨论(0)
提交回复
热议问题