必承其重 | 欲带皇冠
2009-03-25 09:10

在 window.location.hash-更改?


I am using Ajax and hash for navigation.

Is there a way to check if the window.location.hash changed like this?

http://example.com/blah#123 to http://example.com/blah#456

It works if I check it when the document loads.

But if I have #hash based navigation it doesn't work when I press the back button on the browser (so I jump from blah#456 to blah#123).

It shows inside the address box, but I can't catch it with JavaScript.


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • csdnceshi73 喵-见缝插针 6年前

    The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.

    Update to keep this answer fresh:

    If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.

    $(window).on('hashchange', function() {
      //.. work ..

    The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.

    With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).

    In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.

    This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.

    点赞 26 评论 复制链接分享
  • csdnceshi59 ℙℕℤℝ 12年前

    HTML5 specifies a hashchange event. This event is now supported by all modern browsers. Support was added in the following browser versions:

    • Internet Explorer 8
    • Firefox 3.6
    • Chrome 5
    • Safari 5
    • Opera 10.6
    点赞 27 评论 复制链接分享
  • csdnceshi51 旧行李 6年前

    I've been using path.js for my client side routing. I've found it to be quite succinct and lightweight (it's also been published to NPM too), and makes use of hash based navigation.

    path.js NPM

    path.js GitHub

    点赞 10 评论 复制链接分享
  • csdnceshi65 larry*wei 4年前

    I was using this in a react application to make the URL display different parameters depending what view the user was on.

    I watched the hash parameter using

    window.addEventListener('hashchange', doSomethingWithChangeFunction());


    doSomethingWithChangeFunction () { 
        // Get new hash value
        let urlParam = window.location.hash;
        // Do something with new hash value

    Worked a treat, works with forward and back browser buttons and also in browser history.

    点赞 9 评论 复制链接分享
  • weixin_41568208 北城已荒凉 10年前
    var page_url = 'http://www.yoursite.com/'; // full path leading up to hash;
    var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123
    function TrackHash() {
        if (document.location != page_url + current_url_w_hash) {
            window.location = document.location;
        return false;
    var RunTabs = setInterval(TrackHash, 200);

    That's it... now, anytime you hit your back or forward buttons, the page will reload as per the new hash value.

    点赞 8 评论 复制链接分享
  • csdnceshi71 Memor.の 12年前

    A decent implementation can be found at http://code.google.com/p/reallysimplehistory/. The only (but also) problem and bug it has is: in Internet Explorer modifying the location hash manually will reset the entire history stack (this is a browser issue and it cannot be solved).

    Note, Internet Explorer 8 does have support for the "hashchange" event, and since it is becoming part of HTML5 you may expect other browsers to catch up.

    点赞 8 评论 复制链接分享
  • csdnceshi51 旧行李 11年前

    You could easily implement an observer (the "watch" method) on the "hash" property of "window.location" object.

    Firefox has its own implementation for watching changes of object, but if you use some other implementation (such as Watch for object properties changes in JavaScript) - for other browsers, that will do the trick.

    The code will look like this:

            console.log("the window's hash value has changed from "+oldval+" to "+newVal);

    Then you can test it:

    var myHashLink = "home";
    window.location = window.location + "#" + myHashLink;

    And of course that will trigger your observer function.

    点赞 8 评论 复制链接分享
  • weixin_41568208 北城已荒凉 11年前

    Ben Alman has a great jQuery plugin for dealing with this: http://benalman.com/projects/jquery-hashchange-plugin/

    If you're not using jQuery it may be an interesting reference to dissect.

    点赞 8 评论 复制链接分享
  • csdnceshi55 ~Onlooker 10年前

    Note that in case of Internet Explorer 7 and Internet Explorer 9 the if statment will give true (for "onhashchange" in windows), but the window.onhashchange will never fire, so it's better to store hash and check it after every 100 millisecond whether it's changed or not for all versions of Internet Explorer.

        if (("onhashchange" in window) && !($.browser.msie)) {
             window.onhashchange = function () {
             // Or $(window).bind( 'hashchange',function(e) {
             //       alert(window.location.hash);
             //   });
        else {
            var prevHash = window.location.hash;
            window.setInterval(function () {
               if (window.location.hash != prevHash) {
                  prevHash = window.location.hash;
            }, 100);

    EDIT - Since jQuery 1.9, $.browser.msie is not supported. Source: http://api.jquery.com/jquery.browser/

    点赞 7 评论 复制链接分享
  • csdnceshi72 谁还没个明天 11年前

    Firefox has had an onhashchange event since 3.6. See window.onhashchange.

    点赞 5 评论 复制链接分享
  • csdnceshi72 谁还没个明天 12年前

    There are a lot of tricks to deal with History and window.location.hash in IE browsers:

    • As original question said, if you go from page a.html#b to a.html#c, and then hit the back button, the browser doesn't know that page has changed. Let me say it with an example: window.location.href will be 'a.html#c', no matter if you are in a.html#b or a.html#c.

    • Actually, a.html#b and a.html#c are stored in history only if elements '<a name="#b">' and '<a name="#c">' exists previously in the page.

    • However, if you put an iframe inside a page, navigate from a.html#b to a.html#c in that iframe and then hit the back button, iframe.contentWindow.document.location.href changes as expected.

    • If you use 'document.domain=something' in your code, then you can't access to iframe.contentWindow.document.open()' (and many History Managers does that)

    I know this isn't a real response, but maybe IE-History notes are useful to somebody.

    点赞 4 评论 复制链接分享
  • csdnceshi62 csdnceshi62 11年前

    Another great implementation is jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.

    Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!

    点赞 1 评论 复制链接分享
  • weixin_41568196 撒拉嘿哟木头 12年前

    I used a jQuery plugin, HUtil, and wrote a YUI History like interface on top of it.

    Check it out once. If you need help I can help.

    点赞 评论 复制链接分享