Modifying a query string without reloading the page

前端 未结 5 2091
北荒
北荒 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:49

    I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.

    function insertUrlParam(key, value) {
        if (history.pushState) {
            let searchParams = new URLSearchParams(window.location.search);
            searchParams.set(key, value);
            let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
            window.history.pushState({path: newurl}, '', newurl);
        }
    }
    

提交回复
热议问题