Modifying a query string without reloading the page

前端 未结 5 2093
北荒
北荒 2020-11-29 17:18

I am creating a photo gallery, and would like to be able to change the query string and title when the photos are browsed.

The behavior I am looking for is often see

5条回答
  •  天涯浪人
    2020-11-29 17:56

    Building off of Fabio's answer, I created two functions that will probably be useful for anyone stumbling upon this question. With these two functions, you can call insertParam() with a key and value as an argument. It will either add the URL parameter or, if a query param already exists with the same key, it will change that parameter to the new value:

    //function to remove query params from a URL
    function removeURLParameter(url, parameter) {
        //better to use l.search if you have a location/link object
        var urlparts= url.split('?');   
        if (urlparts.length>=2) {
    
            var prefix= encodeURIComponent(parameter)+'=';
            var pars= urlparts[1].split(/[&;]/g);
    
            //reverse iteration as may be destructive
            for (var i= pars.length; i-- > 0;) {    
                //idiom for string.startsWith
                if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
                    pars.splice(i, 1);
                }
            }
    
            url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
            return url;
        } else {
            return url;
        }
    }
    
    //function to add/update query params
    function insertParam(key, value) {
        if (history.pushState) {
            // var newurl = window.location.protocol + "//" + window.location.host + search.pathname + '?myNewUrlQuery=1';
            var currentUrlWithOutHash = window.location.origin + window.location.pathname + window.location.search;
            var hash = window.location.hash
            //remove any param for the same key
            var currentUrlWithOutHash = removeURLParameter(currentUrlWithOutHash, key);
    
            //figure out if we need to add the param with a ? or a &
            var queryStart;
            if(currentUrlWithOutHash.indexOf('?') !== -1){
                queryStart = '&';
            } else {
                queryStart = '?';
            }
    
            var newurl = currentUrlWithOutHash + queryStart + key + '=' + value + hash
            window.history.pushState({path:newurl},'',newurl);
        }
    }
    

提交回复
热议问题