How to detect if URL has changed after hash in JavaScript

后端 未结 17 1704
無奈伤痛
無奈伤痛 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:39

    I created this, just add the function as an argument and whenever the link has any changes it will run the function returning the old and new url

    I created this, just add the function as an argument and whenever the link has any changes it will run the function returning the old and new url

    // on-url-change.js v1 (manual verification)
    let onUrlChangeCallbacks = [];
    let onUrlChangeTimestamp = new Date() * 1;
    function onUrlChange(callback){
        onUrlChangeCallbacks.push(callback);
    };
    onUrlChangeAutorun();
    function onUrlChangeAutorun(){
        let oldURL = window.location.href;
        setInterval(function(){
            let newURL = window.location.href;
            if(oldURL !== newURL){
                let event = {
                    oldURL: oldURL,
                    newURL: newURL,
                    type: 'urlchange',
                    timestamp: new Date() * 1 - onUrlChangeTimestamp
                };
                oldURL = newURL;
                for(let i = 0; i < onUrlChangeCallbacks.length; i++){
                    onUrlChangeCallbacks[i](event);
                };
            };
        }, 25);
    };
    

提交回复
热议问题