How to detect if URL has changed after hash in JavaScript

后端 未结 17 1621
無奈伤痛
無奈伤痛 2020-11-22 17:02

How can I check if a URL has changed in JavaScript? For example, websites like GitHub, which use AJAX, will append page information after a # symbol to create a unique URL w

17条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 17:40

    Add a hash change event listener!

    window.addEventListener('hashchange', function(e){console.log('hash changed')});
    

    Or, to listen to all URL changes:

    window.addEventListener('popstate', function(e){console.log('url changed')});
    

    This is better than something like the code below because only one thing can exist in window.onhashchange and you'll possibly be overwriting someone else's code.

    // Bad code example
    
    window.onhashchange = function() { 
         // Code that overwrites whatever was previously in window.onhashchange  
    }
    

提交回复
热议问题