How can I detect an address bar change with JavaScript?

后端 未结 4 1799

I have a Ajax heavy application that may have a URL such as

http://example.com/myApp/#page=1

When a user manipulates the site, the address ba

相关标签:
4条回答
  • 2020-11-27 15:53

    check the current address periodically using setTimeout/interval:

     var oldLocation = location.href;
     setInterval(function() {
          if(location.href != oldLocation) {
               // do your action
               oldLocation = location.href
          }
      }, 1000); // check every second
    
    0 讨论(0)
  • 2020-11-27 15:53

    SWFaddress is an excellent library for these types of things.

    0 讨论(0)
  • 2020-11-27 16:03

    HTML5 introduces a hashchange event which allows you to register for notifications of url hash changes without polling for them with a timer.

    It it supported by all major browsers (Firefox 3.6, IE8, Chrome, other Webkit-based browsers), but I'd still highly suggest to use a library which handles the event for you - i.e. by using a timer in browsers not supporting the HTML5 event and using the event otherwise.

    window.onhashchange = function() {
        alert("hashtag changed");
    };
    

    For further information on the event, see https://developer.mozilla.org/en/dom/window.onhashchange and http://msdn.microsoft.com/en-us/library/cc288209%28VS.85%29.aspx.

    0 讨论(0)
  • 2020-11-27 16:03

    You should extend the location object to expose an event that you can bind to.

    ie:

    window.location.prototype.changed = function(e){};
    
    (function() //create a scope so 'location' is not global
    {
        var location = window.location.href;
        setInterval(function()
        {
            if(location != window.location.href)
            {
                location = window.location.href;
                window.location.changed(location);
            }
        }, 1000);
    })();
    
    window.location.changed = function(e)
    {
        console.log(e);//outputs http://newhref.com
        //this is fired when the window changes location
    }
    
    0 讨论(0)
提交回复
热议问题