Javascript – Fetch getting undefined url variable on window.popstate

Hi there!

I’m trying to fetch content from a php page. I have a fetch call + a history.pushState firing on click, which are both working fine, but window.popstate is returning an error when going back by pressing the browser’s back button. The error is, that window.popstate doesn’t know what url to fetch when going back.

Unfortunately I can’t figure out how to pass the right url variable to window.popstate.

// the code stripped fetch function
        var load = function(url){
            fetch(url, {
                method: "GET"
            }).then(function(response) {
                    response.text().then(function(text) {

                        // parsing and temporary placing fetched content into a fragment
                        var content = new DOMParser().parseFromString(text, "text/html"),
                        bodyPart = content.querySelector('main'),
                        fragmentElement = document.createDocumentFragment(),
                        tempElement = fragmentElement.appendChild(bodyPart);

                        // replacing the current content with the fragment
                        document.body.replaceChild(tempElement, document.querySelector('main')); 

                        // need to assign the fetch on click function again, otherwise it won't work on the dynamically added (the fetched) links
                        clickOnPJAXLink();

                    });
                });
            }

            // the click function if clicking on any link function to start fetching content
            var clickOnPJAXLink = function(url) {
                document.querySelectorAll('A').forEach(a => {
                    a.addEventListener('click', (e) => {
                        e.preventDefault();
                        var url = e.currentTarget.getAttribute("href");
                        load(url);                          
                        history.pushState(url, "sometitle", url);
                    });
                });
            }

            // load the function initially on the home page
            clickOnPJAXLink();

            // popstate for back button
            window.addEventListener('popstate', function (e) {
                var state = e.state;
                if (state !== null) {
                    load(url);
                    console.log(url)
                }
            });

The window.popstate returns the error, that var url is undefined and thus of course cannot fetch the before (the history back) content.

Many thanks for any tips!